UIView
UIView?*view?=?[[UIView?alloc]?init];
view.backgroundColor?=?[UIColor?blackColor];
view.layer.cornerRadius?=3.f;
//?以下兩行胖烛,任寫一行
view.layer.masksToBounds?=?NO;
view.clipToBounds?=?NO;
//?以下兩行词渤,千萬不要加!
view.layer.masksToBounds?=?YES;
view.clipToBounds?=?YES;
注意點:UIView 只要設(shè)置圖層的 cornerRadius 屬性即可(不明白的話朝捆,可以看看官方文檔里對 cornerRadius 的描述),如果設(shè)置 layer.masksToBounds = YES瞪浸,會造成不必要的離屏渲染砰苍。
UITextField
UITextField有兩種實現(xiàn)方法
//?天然支持設(shè)置圓角邊框
UITextField?*textField?=?[[UITextField?alloc]?init];
textField.borderStyle?=?UITextBorderStyleRoundedRect;
//?與?UIView?類似
UITextField?*textField?=?[[UITextField?alloc]?init];
textField.layer.cornerRadius?=?cornerRadius;
UITextView
//?與?UIView?類似
UITextView?*textView?=?[[UITextView?alloc]?init];
textView.layer.cornerRadius?=?cornerRadius;
UILabel
UILabel?*label=?[[UILabel?alloc]?init];
//?重點在此!谚咬!設(shè)置視圖的圖層背景色,千萬不要直接設(shè)置?label.backgroundColor
label.layer.backgroundColor?=?[UIColor?grayColor].CGColor;
label.layer.cornerRadius?=?cornerRadius;
UIButton
說明:UIButton 的背景圖片通孽,如果是復(fù)雜的圖片序宦,可以依靠 UI 切圖來實現(xiàn)。如果是簡單的純色背景圖片背苦,可以利用代碼繪制帶圓角的圖片互捌。
UIButton?*button?=?[UIButton?buttonWithType:UIButtonTypeCustom];
//?設(shè)置?UIButton?的背景圖片。
[button?setBackgroundImage:image?forState:UIControlStateNormal];
背景圖片繪制方法
+?(UIImage?*)pureColorImageWithSize:(CGSize)size?color:(UIColor?*)color?cornRadius:(CGFloat)cornRadius?{
UIView?*view?=?[[UIView?alloc]?initWithFrame:CGRectMake(0.0f,0.0f,?size.width,?size.height)];
view.backgroundColor?=?color;
view.layer.cornerRadius?=?cornerRadius;
//?下面方法行剂,第一個參數(shù)表示區(qū)域大小秕噪。第二個參數(shù)表示是否是非透明的。如果需要顯示半透明效果厚宰,需要傳NO腌巾,否則傳YES遂填。第三個參數(shù)是屏幕密度
UIGraphicsBeginImageContextWithOptions(view.bounds.size,?NO,?[UIScreen?mainScreen].scale);
[view.layer?renderInContext:UIGraphicsGetCurrentContext()];
UIImage?*image?=?UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
returnimage;
}
UIImageView
UIImageView 有三種方式實現(xiàn)圓角:
貝塞爾曲線切割圓角
-?(UIImageView?*)roundedRectImageViewWithCornerRadius:(CGFloat)cornerRadius?{
UIBezierPath?*bezierPath?=?[UIBezierPath?bezierPathWithRoundedRect:self.bounds?cornerRadius:cornerRadius];
CAShapeLayer?*layer?=?[CAShapeLayer?layer];
layer.path?=?bezierPath.CGPath;
self.layer.mask?=?layer;
returnself;
}
繪制四個角的遮罩(使用場景受限)
在 UIImageView 上添加一個四個角有內(nèi)容,其它部分是透明的視圖澈蝙,只對 UIImageView 圓角部分進行遮擋吓坚。但要保證被遮擋的部分背景色要與周圍背景相同,避免穿幫灯荧。所以當(dāng) UIImageView 處于一個復(fù)雜的背景時礁击,是不適合使用這個方法的。
最不推薦做法(當(dāng)一個頁面只有少量圓角圖片時才推薦使用)
UIImageView?*imageView?=?[[UIImageView?alloc]?init];
imageView.layer.cornerRadius?=5.f;
imageView.layer.masksToBounds?=?YES;