前言
在iOS開發(fā)中我們經(jīng)常會(huì)遇到給UIImageView添加圓角,如:給用戶頭像設(shè)置圓角等。在這里記錄一下使用過的三種方法。
方法一:通過設(shè)置UIView的layer來設(shè)置圓角
UIImageView *imgView = [UIImageView new];
imgView.image = [UIImage imageNamed:@"aa"];
imgView.layer.cornerRadius = imgView.frame.size.width / 2;
imgView.layer.masksToBounds = YES;
此方法的有個(gè)缺點(diǎn)是:會(huì)強(qiáng)制Core Animation提前渲染屏幕的離屏繪制, 而離屏繪制就會(huì)給性能帶來負(fù)面影響,會(huì)有卡頓的現(xiàn)象出現(xiàn)
方法二:通過Graphics繪制圖片,將圖片裁剪成圓角
- (UIImage *)clipImage1:(UIImage *)image {
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0);
// 獲取上下文
CGContextRef contextRef = UIGraphicsGetCurrentContext();
// 添加一個(gè)圓
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
CGContextAddEllipseInRect(contextRef, rect);
CGContextClip(contextRef);
// 畫圖片
[image drawInRect:rect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
裁剪后設(shè)置圖片即可
方法三: 依然是繪制圖片,這次是通過貝塞爾曲線繪制圖片
- (UIImage *)clipImage2:(UIImage *)image {
UIGraphicsBeginImageContextWithOptions(image.size, NO, 1.0);
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
[[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:image.size.width / 2] addClip];
[image drawInRect:rect];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
繪制后設(shè)置UIImageView的圖片即可
總結(jié):
以上設(shè)置圖片圓角的三種方法,在使用過程中各有優(yōu)缺點(diǎn),需要根據(jù)實(shí)際情況具體判斷使用方法。
另外推薦一下我的導(dǎo)航欄聯(lián)動(dòng)庫(kù):GKNavigationController