這篇文章主要給大家介紹了關於iOS設置圓角的4種方法,並給大家附上了性能評測,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧
四種設置圓角的方法
從網上收集了各種設置圓角的方法,總結起來有以下四種:
1、設置 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、混合圖層,用一張鏤空的透明圖片作遮罩
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;
四種方法性能測試
網上流傳兩個結論:
- 第一種方法會引發離屏渲染,所以是最慢的;
- 據說第四種是效率最高的。
事實情況如何呢?
爲了驗證網上的結論,需要找一種性能比較的方法,這裏用 Instrument 的測試 FPS (幀數)作爲性能直觀的比較值,測試過程如下:
- 搭建collectionView 工程,連續刷新顯示 1萬個cell,每個cell使用相同圖片,排除不同照片帶來的差異;
- 在真機下運行分別運行四種方法,用 Instrument 記錄,並計算平均FPS;
- 爲保證平均值準確,去掉頭尾幀數率過低的時間段。
1. 設置 layer 的 cornerRadius
2. 用貝塞爾曲線作 mask 圓角
3. 重新繪製圓角
4. 混合圖層,用一張鏤空的透明圖片作遮罩
結果排名如下
3 > 1 > 2 > 4
一點點優化
第四種方式不但墊底,而且出奇的慢,說明我們的實現有明顯的問題,觀察代碼,發現原來的代碼沒有考慮 cell 複用,cove 視圖被反覆添加到cell,哪有不慢的道理!!! 於是作以下優化:
// 4. 混合圖層,用一張鏤空的透明圖片作遮罩 (優化版) 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的重複添加,FPS 有了明顯的回升:
4.(優化版)
優化後的排名: 3 > 4 > 1 > 2
結論
測試的結論與網上流傳的幾乎完全不同,分析一下造成這種情況的原因:
- 蘋果在iOS9後優化了 cornerRadius 的繪圖方式,方法1不再需要離屏渲染。
- 方法3基於單張位圖運算,方法2使用了矢量並與位圖疊加,導致運算量上升,觀察圖2的GPU運算量高達 80.2%,證明了這一推斷。
實際開發建議
- 方法1 設置簡單,性能差別不明顯,簡單圓角場景下推薦使用。
- 方法4 基於透明位圖,可用於異形遮罩,但需要根據圖片大小做多張特殊位圖,請根據實際情況選擇。
- 在位圖尺寸很大,數量很多的情況下,用方法3,但要注意內存警告,最好配合緩存機制使用,避免因內存溢出而崩潰。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對神馬文庫的支持。