在 iOS 中,讓圖片或視圖呈現圓角,最常見的方式是設定 layer 的 cornerRadius 與 masksToBounds。若需要圓形頭像,可將 cornerRadius 設為寬高的一半。
UIImageView *headImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"portrait_bg_80"]]; headImage.frame = CGRectMake(10, 10, 35, 35); headImage.layer.cornerRadius = 35 / 2.0; headImage.layer.masksToBounds = YES; headImage.layer.borderWidth = 1; headImage.layer.borderColor = [UIColor whiteColor].CGColor;
若只需要一般圓角,可取得 imageView.layer,設定 cornerRadius 與 masksToBounds。注意通常要在圖片或視圖加入畫面後再設定,以避免外觀未更新。
cell.userPicView.layer.masksToBounds = YES; cell.userPicView.layer.cornerRadius = 6.0;
如果是 UIView,也可直接設定 cornerRadius、borderWidth 與 borderColor。
除了 layer 屬性,也可在繪製時建立圓角路徑,或使用 Core Graphics 繪製遮罩。這類方式較適合需要動態產生圖片或特殊形狀的場景。
使用圓角前,通常需要導入 QuartzCore 框架。若需要保持圖片比例,可設定 contentMode 為 UIViewContentModeScaleAspectFit。若只想讓特定幾個角圓滑,則需要建立自訂遮罩路徑。