圓角在 iOS 上有三種常見寫法,複雜度與效能表現差異不小。以下逐一說明並附上可直接執行的範例。
最簡單的一種,只需兩個屬性:
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; // 設定圓角半徑 imageView.layer.cornerRadius = imageView.frame.size.width / 2; // 裁掉超出邊界的部分 imageView.layer.masksToBounds = YES; [self.view addSubview:imageView];
缺點是會觸發離屏渲染,在大量 cell 或快速滾動的清單上容易掉帧,因此正常開發中反而用得不多。
把圓角直接畫進圖片內容,之後顯示時就是普通點陣圖:
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"1"];
// 開始繪圖
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
// 用貝茲曲線畫出圓形並設定為裁剪區域
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds
cornerRadius:imageView.frame.size.width] addClip];
[imageView drawInRect:imageView.bounds];
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
// 結束繪圖
UIGraphicsEndImageContext();
[self.view addSubview:imageView];
要注意 UIGraphicsBeginImageContextWithOptions 的第三個參數傳 1.0 會強制以 1 倍圖渲染,在 Retina 螢幕上畫出來的圖會偏模糊。實務上應傳 0 或 [UIScreen mainScreen].scale 讓系統採用裝置原生解析度。
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"1"];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds
byRoundingCorners:UIRectCornerAllCorners
cornerRadii:imageView.bounds.size];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = imageView.bounds; // 設定大小
maskLayer.path = maskPath.CGPath; // 設定遮罩形狀
imageView.layer.mask = maskLayer;
[self.view addSubview:imageView];
}
@end
使用 byRoundingCorners:cornerRadii: 這組 API 的好處是可以只對特定轉角設圓角,例如上方兩角圓、下方兩角直角的卡片,用方式一就做不到。
三種方式中,第三種整體表現最好:記憶體消耗最低、渲染速度快,而且支援單角設定。若只是臨時改個小元件,方式一寫起來最快;若圖片本身會被重複使用,方式二把成本一次性付清也相當划算。