您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 按鈕圓角實作:指定四角範圍的 UIBezierPath 做法

編輯:iOS 開發綜合

iOS 介面中圓角按鈕幾乎無所不在。最簡單的方式是 layer.cornerRadius,但那會把四個角一起處理;若只想讓其中幾個角圓潤,就得動用 UIBezierPath 搭配 mask。

先認識四個角的常量

     左上:UIRectCornerTopLeft
     左下:UIRectCornerBottomLeft
     右上:UIRectCornerTopRight
     右下:UIRectCornerBottomRight

這些常量可以用位元或運算子 | 自由組合。

實作程式碼

 UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(50, 60, 80, 40)];
button.backgroundColor = [UIColor orangeColor];
[self.view addSubview:button];

// 這裡只處理左上與左下兩角
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:button.bounds
                                              byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopLeft
                                                    cornerRadii:CGSizeMake(8, 8)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = button.bounds;
maskLayer.path  = maskPath.CGPath;
button.layer.mask = maskLayer;

效果

幾個實務提醒

mask 不會隨尺寸自動更新。layer.mask 的 frame 是在設定當下固定下來的。若按鈕日後因 Auto Layout 或程式碼改了尺寸,圓角遮罩不會跟著變,畫面會出現缺口。這類情況建議改寫 layoutSubviews 重新產生 mask,或直接改用 layer.maskedCorners(iOS 11 之後提供)搭配 cornerRadius。

cornerRadii 的兩個值分別對應 x 與 y。寫成 CGSizeMake(8, 8) 是正圓角;若兩值不同,會得到橢圓弧。

四個角全圓的簡寫。如果確實四個角都要圓,不必繞這一圈,直接一行搞定:

 button.layer.cornerRadius = 8;
 button.clipsToBounds = YES;   // 少了這行,子檢視不會被裁切

clipsToBounds(或 masksToBounds)經常被遺漏,導致圓角看起來「只有背景圓了,圖片還是方的」。

以上就是 iOS 按鈕圓角設定的做法,希望對大家的開發有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved