OC 版本:
創(chuàng)建UIImageView 分類:
xxx.m
@implementation UIImage (ImageCIr)
/** 設(shè)置圓形圖片(放到分類中使用) */
+ (nullable UIImage *)clipCircleImageWithImage:(nullable UIImage *)image circleRect:(CGRect)rect {
//1搔耕、開(kāi)啟上下文
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
//2隙袁、設(shè)置裁剪區(qū)域
UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect:rect];
[path addClip];
//3、繪制圖片
[image drawAtPoint:CGPointZero];
//4弃榨、獲取新圖片
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
//5菩收、關(guān)閉上下文
UIGraphicsEndImageContext();
//6、返回新圖片
return newImage;
}
xxx.h
+ (nullable UIImage *)clipCircleImageWithImage:(nullable UIImage *)image circleRect:(CGRect)rect;
使用:
UIImageView *roundImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, 200, 200)];
UIImage *image = [UIImage imageNamed:@"zzz"];
roundImg.image = [UIImage clipCircleImageWithImage:image circleRect:roundImg.frame];
[self.view addSubview:roundImg];
Swift版本:
extension UIImageView {
/// 圖片切成圓形
///
/// - Parameters:
/// - image: 傳入處理的圖片
/// - rect: 切割的大小
/// - Returns: 返回切割的t圓形圖片
func clipCircleImage(with image: UIImage?, circleRect rect: CGRect) -> UIImage? {
//1鲸睛、開(kāi)啟上下文
UIGraphicsBeginImageContextWithOptions(image?.size ?? CGSize.zero, false, 0)
//2娜饵、設(shè)置裁剪區(qū)域
let path = UIBezierPath(ovalIn: rect)
path.addClip()
//3、繪制圖片
image?.draw(at: CGPoint.zero)
//4官辈、獲取新圖片
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
//5箱舞、關(guān)閉上下文
UIGraphicsEndImageContext()
//6、返回新圖片
return newImage
}
}
調(diào)用:
let img = UIImageView.init(frame: CGRect.init(x: 0, y: 64, width: 200, height: 200))
let customImg = UIImage.init(named: "aaa")
img.image = img.clipCircleImage(with: customImg, circleRect: CGRect(x: 0, y: 0, width: img.frame.width, height: img.frame.height))
view.addSubview(img)