標籤:
我們經常需要把一些不是圓形的圖片剪下成圓形後來使用,比如QQ頭像,微博頭像等都是圓形,那麼問題來了,該怎麼把一張不是圓形的圖片剪下成圓形呢?下面就是其中一種可以實現這種需求的方法: 具體實現思路:1.假設邊框寬度為BorderW2.開啟的圖片內容相關的尺寸就應該是原始圖片的寬高分別加上兩倍的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.開啟一個和原始圖片一樣大小的位元影像上下文. 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(); 抽取分類方法: 根據傳入的圖片,產生一終帶有邊框的圓形圖片.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;
}
iOS之帶有邊框的圓形圖片裁剪