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

iPhone 開發筆記(7):用 Layer 做出圓角按鈕

編輯:iOS 開發綜合

製作圓角按鈕的方法有很多種,這裡介紹用 layer 的做法。雖然 layer 在效能上未必是最快的選擇,但就效果而言相當漂亮——只要設定 cornerRadius、borderWidth 與 borderColor,就能輕鬆做出帶圓角與描邊的樣式。

效果預覽

實作程式碼

下面的範例是「UIImageView + 透明 button」的組合:用 UIImageView 顯示圖片並設定圓角邊框,再疊上一個透明按鈕接收點擊。直接改 button 的 layer 我沒試過,不過原理應該差不多。以第一個為例:

UIImageView *imageView1 = [[UIImageView alloc] init];
imageView1.frame = CGRectMake(23.75, 16.6, 75, 75);
imageView1.image = [UIImage imageNamed:@"menu1.png"];
imageView1.layer.MasksToBounds = YES;          // 讓內容被圓角裁切
imageView1.layer.cornerRadius = 10.0;          // 圓角半徑
imageView1.layer.borderWidth = 2;              // 邊框寬度
imageView1.layer.borderColor = [[UIColor colorWithRed:161/255.0
                                               green:47/255.0
                                                blue:47/255.0
                                               alpha:1] CGColor];
imageView1.backgroundColor = [UIColor colorWithRed:161/255.0
                                            green:47/255.0
                                             blue:47/255.0
                                            alpha:1];

其餘的 imageView2 到 imageView6 做法完全相同,只是換掉 frame 位置與 imageName(menu2.png~menu6.png),排成兩列三行的配置:

UIImageView *imageView2 = [[UIImageView alloc] init];
imageView2.frame = CGRectMake(122.5, 16.6, 75, 75);
imageView2.image = [UIImage imageNamed:@"menu2.png"];
imageView2.layer.MasksToBounds = YES;
imageView2.layer.cornerRadius = 10.0;
imageView2.layer.borderWidth = 2;
imageView2.layer.borderColor = /* 同上 */ CGColor;
// imageView3 ~ imageView6 依此類推,調整 frame 與 imageName

幾個重點屬性:cornerRadius 決定圓角大小;borderWidth 與 borderColor 控制描邊;而 MasksToBounds = YES 是關鍵——不設這個,圖片內容會超出圓角、露出直角。若還想讓圓角外的陰影正常顯示,則可改用 shadowPath 或外層包一個 view 的方式,避免 MasksToBounds 把陰影也一起裁掉。

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