在 iOS 中,若要讓 UIView、UIButton、UIImageView 等元件顯示圓角,通常會透過其 layer 屬性設定。這方式簡單直接,很適合用於卡片、頭像、標籤與浮層。
zheZhaoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 120)]; [zheZhaoView setBackgroundColor:[UIColor colorWithWhite:0.3f alpha:0.8f]]; zheZhaoView.layer.cornerRadius = 10; zheZhaoView.layer.borderWidth = 0; zheZhaoView.layer.borderColor = [[UIColor grayColor] CGColor]; zheZhaoView.layer.masksToBounds = YES; [self addSubview:zheZhaoView];
cornerRadius 控制圓角半徑,數值越大圓角越明顯。borderWidth 設定邊框寬度,borderColor 設定邊框顏色。masksToBounds 設為 YES 時,子檢視或內容會被裁切到圓角範圍內。
若只需要背景圓角,可保持 masksToBounds 為 NO;若圖片或子檢視也要跟著裁切,則需設為 YES。另外,大量動態更新圓角時,可搭配效能工具觀察是否造成繪製負擔。