iOS 把圖片裁剪成圓形
阿新 • • 發佈:2019-01-22
原圖:
圓形圖片裁剪效果:
裁剪成帶邊框的圓形圖片:
核心程式碼:
#import <UIKit/UIKit.h>
@interface UIImage (image)
/**
* 生成一張圓形圖片
*
* @param image 要裁剪的圖片
*
* @return 生成的圓形圖片
*/
+ (UIImage *)imageWithClipImage:(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 *)imageWithClipImage:(UIImage *)image{
+
//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();
return newImage;
}
+ (UIImage *)imageWithBorder:(CGFloat)borderW color:(UIColor *)borderColor 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)];
[borderColor set];
[path fill];
//3.繪製一個小圓,把小圓設定成裁剪區域
UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];
[clipPath addClip];
//4.把圖片繪製到上下文當中
[image drawAtPoint:CGPointMake(borderW, borderW)];
//5.從上下文當中取出圖片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//6.關閉上下文
UIGraphicsEndImageContext();
return newImage;
}