具體實現思路:
- 1.假設邊框寬度為BorderW
- 2.開啟的圖片上下文的尺寸就應該是原始圖片的寬高分別加上兩倍的BorderW,這樣開啟的目的是為了不讓原始圖片變形.
- 3.在上下文上面添加一個圓形填充路徑.位置從(0,0)點開始,寬高和上下文尺寸一樣大.設置顏色為要設置的邊框顏色.
- 4.繼續在上下文上面添加一個圓形路徑,這個路徑為裁剪路徑.
它的x,y分別從BorderW這個點開始.寬度和高度分別和原始圖片的寬高一樣大.將繪制的這個路徑設為裁剪區域. - 5.把原始路徑繪制到上下文當中.繪制的位置和是裁剪區域的位置相同,x,y分別從border開始繪制.
- 6.從上下文狀態當中取出圖片.
- 7.關閉上下文狀態.
圖形參照:
3.gif
加載要裁剪的圖片
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;```