iOS知多少Objective C开发

iOS之带有边框的圆形图片裁剪

2016-03-11  本文已影响788人  onlychenj

具体实现思路:

图形参照:


3.gif
加载要裁剪的图片

UIImage *image = [UIImage imageNamed:@"阿狸头像"];

UIGraphicsBeginImageContextWithOptions(size,NO,0);```
 -  2.绘制一个大圆,填充
``` UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];    
[[UIColor blueColor] set];
[path fill];```
 -   3.添加一个裁剪区域.
```path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];
[path addClip];```
 -   4.把图片绘制到裁剪区域当中.
 ```[image drawAtPoint:CGPointMake(borderW, borderW)];```
 -   5.生成一张新图片.
```UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();```
 -   6.关闭上下文.
 ```UIGraphicsEndImageContext();```

######抽取分类方法:

```根据传入的图片,生成一终带有边框的圆形图片.
borderW边框宽度
borderColor:边框颜色
image:要生成的原始图片.
+ (UIImage *)imageWithBorderW:(CGFloat)borderW borderColor:(UIColor *)color image:(UIImage *)image;

+ (UIImage *)imageWithBorderW:(CGFloat)borderW borderColor:(UIColor *)color image:(UIImage *)image;```
  - 1.开启一个和原始图片一样大小的位图上下文.
```CGSize size = CGSizeMake(image.size.width + 2 *borderW, image.size.height + 2 * borderW);
UIGraphicsBeginImageContextWithOptions(size,NO,0);```
  -  2.绘制一个大圆,填充
```UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];   
[[UIColor blueColor] set];
[path fill];```
  -  3.添加一个裁剪区域.
```path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];
[path addClip];```
  -  4.把图片绘制到裁剪区域当中.
```[image drawAtPoint:CGPointMake(borderW, borderW)];```
  -  5.生成一张新图片.
```UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();```
  -  6.关闭上下文.
```UIGraphicsEndImageContext();       return clipImage;```
上一篇下一篇

猜你喜欢

热点阅读