具體實現(xiàn)思路:
- 1.假設(shè)邊框?qū)挾葹锽orderW
- 2.開啟的圖片上下文的尺寸就應(yīng)該是原始圖片的寬高分別加上兩倍的BorderW,這樣開啟的目的是為了不讓原始圖片變形.
- 3.在上下文上面添加一個圓形填充路徑.位置從(0,0)點開始,寬高和上下文尺寸一樣大.設(shè)置顏色為要設(shè)置的邊框顏色.
- 4.繼續(xù)在上下文上面添加一個圓形路徑,這個路徑為裁剪路徑.
它的x,y分別從BorderW這個點開始.寬度和高度分別和原始圖片的寬高一樣大.將繪制的這個路徑設(shè)為裁剪區(qū)域. - 5.把原始路徑繪制到上下文當(dāng)中.繪制的位置和是裁剪區(qū)域的位置相同,x,y分別從border開始繪制.
- 6.從上下文狀態(tài)當(dāng)中取出圖片.
- 7.關(guān)閉上下文狀態(tài).
圖形參照:
3.gif
加載要裁剪的圖片
UIImage *image = [UIImage imageNamed:@"阿貍頭像"];
- 0.設(shè)置邊框大小.
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.添加一個裁剪區(qū)域.
```path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];
[path addClip];```
- 4.把圖片繪制到裁剪區(qū)域當(dāng)中.
```[image drawAtPoint:CGPointMake(borderW, borderW)];```
- 5.生成一張新圖片.
```UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();```
- 6.關(guān)閉上下文.
```UIGraphicsEndImageContext();```
######抽取分類方法:
```根據(jù)傳入的圖片,生成一終帶有邊框的圓形圖片.
borderW邊框?qū)挾?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.添加一個裁剪區(qū)域.
```path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];
[path addClip];```
- 4.把圖片繪制到裁剪區(qū)域當(dāng)中.
```[image drawAtPoint:CGPointMake(borderW, borderW)];```
- 5.生成一張新圖片.
```UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();```
- 6.關(guān)閉上下文.
```UIGraphicsEndImageContext(); return clipImage;```