具体实现思路:
- 1.假设边框宽度为BorderW
- 2.开启的图片上下文的尺寸就应该是原始图片的宽高分别加上两倍的BorderW,这样开启的目的是为了不让原始图片变形.
- 3.在上下文上面添加一个圆形填充路径.位置从(0,0)点开始,宽高和上下文尺寸一样大.设置颜色为要设置的边框颜色.
- 4.继续在上下文上面添加一个圆形路径,这个路径为裁剪路径.
它的x,y分别从BorderW这个点开始.宽度和高度分别和原始图片的宽高一样大.将绘制的这个路径设为裁剪区域. - 5.把原始路径绘制到上下文当中.绘制的位置和是裁剪区域的位置相同,x,y分别从border开始绘制.
- 6.从上下文状态当中取出图片.
- 7.关闭上下文状态.
图形参照:
加载要裁剪的图片
UIImage *image = [UIImage imageNamed:@"阿狸头像"];
- 0.设置边框大小.
CGFloat borderW = 10;
- 1.开启一个和原始图片一样大小的位图上下文.
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;```