本文實例為年夜家引見了IOS裁剪圓形頭像的具體代碼,供年夜家參考,詳細內容以下
- (void)viewDidLoad {
[super viewDidLoad];
//加載圖片
UIImage *image = [UIImage imageNamed:@"菲哥"];
//獲得圖片尺寸
CGSize size = image.size;
//開啟位圖高低文
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
//創立圓形途徑
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
//設置為裁剪區域
[path addClip];
//繪制圖片
[image drawAtPoint:CGPointZero];
//獲得裁剪後的圖片
_imageView.image = UIGraphicsGetImageFromCurrentImageContext();
//封閉高低文
UIGraphicsEndImageContext();
}
再來一張菲哥的頭像

假如想要在圓形頭像外加一個邊框,思緒是先繪制一個年夜圓,然後在這個圓尺寸規模內繪制一個圖片年夜小的圓。
- (void)viewDidLoad {
[super viewDidLoad];
//加載圖片
UIImage *image = [UIImage imageNamed:@"年夜菲哥"];
//設置邊框寬度
CGFloat border = 3;
CGFloat imageWH = image.size.width;
//盤算外圓的尺寸
CGFloat ovalWH = imageWH + 2 * border;
//開啟高低文
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
//畫一個年夜的圓形
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, ovalWH, ovalWH)];
[[UIColor orangeColor]set];
[path fill];
//設置裁剪區域
UIBezierPath *path1 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(border, border, imageWH, imageWH)];
[path1 addClip];
//繪制圖片
[image drawAtPoint:CGPointMake(border, border)];
//從高低文中獲得圖片
_imageView.image = UIGraphicsGetImageFromCurrentImageContext();
//封閉高低文
UIGraphicsEndImageContext();
}
後果如圖:

屏幕截圖代碼:
道理就是把屏幕上控件的layer襯著到高低文中
- (void)viewDidLoad {
[super viewDidLoad];
//開啟高低文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);
//獲得高低文
CGContextRef ctx = UIGraphicsGetCurrentContext();
//把控件上的圖層襯著到高低文
[self.view.layer renderInContext:ctx];
//獲得高低文中的圖片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//封閉高低文
UIGraphicsEndImageContext();
//保留圖片到相冊
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
以上就是本文的全體內容,願望對年夜家的進修有所贊助。
【iOS若何裁剪圓形頭像】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!