四種設(shè)置圓角的方法
從網(wǎng)上收集了各種設(shè)置圓角的方法,總結(jié)起來(lái)有以下四種:
1、設(shè)置 layer 的 cornerRadius
view.layer.masksToBounds = YES;view.layer.cornerRadius = imgSize.width / 2;
2、用貝塞爾曲線作 mask 圓角
CAShapeLayer *layer = [CAShapeLayer layer];UIBezierPath *aPath = [UIBezierPath bezierPathWithOvalInRect:view.bounds];layer.path = aPath.CGPath;view.layer.mask = layer;
3、重新繪制圓角
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ UIImage *image = view.image; image = [image drawCircleImage]; dispatch_async(dispatch_get_main_queue(), ^{ view.image = image; }); });////////////////////////@implementation UIImage (RoundedCorner)- (UIImage *)drawCircleImage { CGFloat side = MIN(self.size.width, self.size.height); UIGraphicsBeginImageContextWithOptions(CGSizeMake(side, side), false, [UIScreen mainScreen].scale); CGContextAddPath(UIGraphicsGetCurrentContext(), [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, side, side)].CGPath); CGContextClip(UIGraphicsGetCurrentContext()); CGFloat marginX = -(self.size.width - side) / 2.f; CGFloat marginY = -(self.size.height - side) / 2.f; [self drawInRect:CGRectMake(marginX, marginY, self.size.width, self.size.height)]; CGContextDrawPath(UIGraphicsGetCurrentContext(), kCGPathFillStroke); UIImage *output = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return output;}@end
4、混合圖層,用一張鏤空的透明圖片作遮罩
cover@2x.png
UIView *parent = [view superview];UIImageView *cover = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imgSize.width, imgSize.height)];cover.image = [UIImage imageNamed:@"cover"];[parent addSubview:cover];cover.center = view.center;
四種方法性能測(cè)試
網(wǎng)上流傳兩個(gè)結(jié)論:
事實(shí)情況如何呢?
為了驗(yàn)證網(wǎng)上的結(jié)論,需要找一種性能比較的方法,這里用 Instrument 的測(cè)試 FPS (幀數(shù))作為性能直觀的比較值,測(cè)試過(guò)程如下:
1. 設(shè)置 layer 的 cornerRadius
2. 用貝塞爾曲線作 mask 圓角
3. 重新繪制圓角
4. 混合圖層,用一張鏤空的透明圖片作遮罩
結(jié)果排名如下
3 > 1 > 2 > 4
一點(diǎn)點(diǎn)優(yōu)化
第四種方式不但墊底,而且出奇的慢,說(shuō)明我們的實(shí)現(xiàn)有明顯的問(wèn)題,觀察代碼,發(fā)現(xiàn)原來(lái)的代碼沒有考慮 cell 復(fù)用,cove 視圖被反復(fù)添加到cell,哪有不慢的道理!!! 于是作以下優(yōu)化:
// 4. 混合圖層,用一張鏤空的透明圖片作遮罩 (優(yōu)化版)UIView *parent = [view superview];if (![parent viewWithTag:13]) { UIImageView *cover = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, imgSize.width, imgSize.height)]; cover.image = [UIImage imageNamed:@"cover"]; cover.tag = 13; [parent addSubview:cover]; cover.center = view.center;}
這樣避免了View的重復(fù)添加,F(xiàn)PS 有了明顯的回升:
4.(優(yōu)化版)
優(yōu)化后的排名: 3 > 4 > 1 > 2
結(jié)論
測(cè)試的結(jié)論與網(wǎng)上流傳的幾乎完全不同,分析一下造成這種情況的原因:
實(shí)際開發(fā)建議
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選