本文參考: http://www.baidu.com
一說到圓角, 我們最先想到的可能就是
[view.layer setCornerRadius:3];
[view.layer setMasksToBounds:YES];
但這種方法會造成離屏渲染,對性能影響較大, 設置的少了也能用. 但如果是在tableView上使用的話. 對性能的考驗還是很大的. 不推薦使用
- 先說幾個簡單的
1. UITextField
- textField 自身有設置圓角的方法
textField.borderStyle = UITextBorderStyleRoundedRect;
2. UIView(不包括其子類)
UIView * view = [[UIView alloc] init];
view.backgroundColor = [UIColor redColor];
view.layer.cornerRadius = 3.0f;
// 以下兩行,任寫一行
view.layer.masksToBounds = NO;
view.clipToBounds = NO;
// 以下兩行,千萬不要加荠割!
view.layer.masksToBounds = YES;
view.clipToBounds = YES;
*注:UIView 只要設置圖層的 cornerRadius 屬性即可,如果設置 layer.masksToBounds = YES,會造成不必要的離屏渲染。
3. UITextView
// 與 UIView 類似
UITextView *textView = [[UITextView alloc] init];
textView.layer.cornerRadius = cornerRadius;
4. UILabel
UILabel *label = [[UILabel alloc] init];
// 重點在此!拆祈!設置視圖的圖層背景色,千萬不要直接設置 label.backgroundColor
label.layer.backgroundColor = [UIColor grayColor].CGColor;
label.layer.cornerRadius = cornerRadius;
5. UIButton
- button 能夠設置背景圖片, 一般單一背景色的button圓角設置可以通過設置背景圖片來實現(xiàn)
背景圖片可以是找美工要的, 也可以是自己畫的.
/**
* 背景圖片繪制方法
*/
+ (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();
return image;
}
6. UIImageView
imageView 可以通過圖片上的圓角來實現(xiàn)或者使用貝塞爾曲線的方法來實現(xiàn), 這種方法比較麻煩一點, 但是用的多了就好了
- (UIImageView *)roundedRectImageViewWithCornerRadius:(CGFloat)cornerRadius image:(UIImageView *)imageView
{
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:imageView.frame.size.width] addClip];
[imageView drawRect:imageView.bounds];
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageView;
}
還有一種方法 cashapelayer和uibezierpath設置圓角, 也是我比較常用的一種
#import <AVFoundation/AVFoundation.h>
UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"icon"];
UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:imageView.bounds.size];
CAShapeLayer * layer = [[CAShapeLayer alloc] init];
layer.frame = imageView.bounds;
layer.path = path.CGPath;
imageView.layer.mask = layer;
[self.imageView addSubview:imageView];