標籤:
一:圓形圖片的繪製
@interface ViewController ()@property (weak, nonatomic) IBOutlet UIImageView *imageV;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; /** * UIBezierPath:繪製路徑,就是根據路徑對圖形上下文進行構造 */ //0.載入圖片 UIImage *image = [UIImage imageNamed:@"阿狸頭像"]; //1.開啟跟原始圖片一樣大小的上下文 UIGraphicsBeginImageContextWithOptions(image.size, NO, 0); //2.設定一個圓形裁剪地區 //2.1繪製一個圓形 UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)]; //2.2.把圓形的路徑設定成裁剪地區 [path addClip];//超過裁剪地區以外的內容都給裁剪掉 //3.把圖片繪製到上下文當中(超過裁剪地區以外的內容都給裁剪掉) [image drawAtPoint:CGPointZero]; //4.從上下文當中取出圖片 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); //5.關閉上下文 UIGraphicsEndImageContext(); self.imageV.image = newImage; }@end
裁剪圖片思路.
開啟一個圖片上下文.
內容相關的大小和原始圖片保持一樣.以免圖片被展開縮放.
在內容相關的上面添加一個圓形裁剪地區.圓形裁剪地區的半徑大小和圖片的寬度一樣大.
把要裁剪的圖片繪製到圖片上下文當中.
從上下文當中取出圖片.
關閉上下文.
1.如何設定圓形路徑?
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:
CGRectMake(0, 0, image.size.width, image.size.width)];
2.如何把一個路徑設為裁剪地區?
[path addClip];
二:帶邊框的圓形圖片繪製
#import <UIKit/UIKit.h>@interface UIImage (image)/** * 產生一張帶有邊框的圓形圖片 * * @param borderW 邊框寬度 * @param borderColor 邊框顏色 * @param image 要添加邊框的圖片 * * @return 產生的帶有邊框的圓形圖片 */+ (UIImage *)imageWithBorder:(CGFloat)borderW color:(UIColor *)borderColor image:(UIImage *)image;@end
#import "UIImage+image.h"@implementation UIImage (image)+ (UIImage *)imageWithBorder:(CGFloat)borderW color:(UIColor *)borderColor image:(UIImage *)image{ //0.載入圖片 //UIImage *image = [UIImage imageNamed:@"阿狸頭像"]; //1.確定邊框寬度 //CGFloat borderW = 5; //2.開啟一個上下文 CGSize size = CGSizeMake(image.size.width + 2 * borderW, image.size.height + 2 * borderW); UIGraphicsBeginImageContextWithOptions(size, NO, 0); //3.繪製大圓,顯示出來 UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)]; [borderColor set]; [path addClip]; [path fill];//自動將路徑添加到上下文 //4.繪製一個小圓,把小圓設定成裁剪地區 UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)]; [clipPath addClip];//自動將路徑添加到上下文,並且超過裁剪地區的路徑直接裁減掉,此方法會裁減掉超過大圓的部分 //5.把圖片繪製到上下文當中,drawAtPoint畫出的圖片大小和image大小相同 [image drawAtPoint:CGPointMake(borderW, borderW)]; //6.從上下文當中取出圖片 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); //7.關閉上下文 UIGraphicsEndImageContext(); return newImage;}@end
具體實現思路:
1.假設邊框寬度為BorderW
2.開啟的圖片內容相關的尺寸就應該是原始圖片的寬高分別加上兩倍的BorderW,這樣開啟的目的是為了不讓原始圖片變形.
3.在上下文上面添加一個圓形填充路徑.位置從0,0點開始,寬高和上下文尺寸一樣大.設定顏色為要設定的邊框顏色.
4.繼續在上下文上面添加一個圓形路徑,這個路徑為裁剪路徑.
它的x,y分別從BorderW這個點開始.寬度和高度分別和原始圖片的寬高一樣大.
將繪製的這個路徑設為裁剪地區.
5.把原始路徑繪製到上下文當中.繪製的位置和是裁剪地區的位置相同,x,y分別從border開始繪製.
6.從上下文狀態當中取出圖片.
7.關閉上下文狀態.
iOS開發Quzrtz2D 十:圓形圖片的繪製以及加邊框圓形圖片的繪製