第一種方法:通過設置layer的屬性
最簡單的一種,但是很影響性能,一般在正常的開發中使用很少.
UIImageView*imageView = [[UIImageViewalloc]initWithFrame:CGRectMake(100,100,100,100)];
//只需要設置 layer層的兩個屬性
//設置圓角
imageView.layer.cornerRadius = imageView.frame.size.width /2;
//將多余的部分切掉
imageView.layer.masksToBounds =YES;
[self.view addSubview:imageView];
或者在xib中設置屬性
B2CF955B-35C6-44BC-840B-65CA0B9AB6A8.png
第二種方法:使用貝塞爾曲線UIBezierPath和Core Graphics框架畫出一個圓角
UIImageView*imageView = [[UIImageViewalloc]initWithFrame:CGRectMake(100,100,100,100)];
imageView.image = [UIImageimageNamed:@"1"];
//開始對imageView進行畫圖
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size,NO, [UIScreenmainScreen].scale);
//使用貝塞爾曲線畫出一個圓形圖
[[UIBezierPathbezierPathWithRoundedRect:imageView.bounds cornerRadius:imageView.frame.size.width] addClip];
[imageView drawRect:imageView.bounds];
imageView.image =UIGraphicsGetImageFromCurrentImageContext();
//結束畫圖UIGraphicsEndImageContext();
[self.view addSubview:imageView];
第三種方法:使用CAShapeLayer和UIBezierPath設置圓角
首先需要導入
#import"ViewController.h"
@interfaceViewController()
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
UIImageView*imageView = [[UIImageViewalloc]initWithFrame:CGRectMake(100,100,100,100)];
imageView.image = [UIImageimageNamed:@"1"];
UIBezierPath*maskPath = [UIBezierPathbezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCornerscornerRadii:imageView.bounds.size];
CAShapeLayer*maskLayer = [[CAShapeLayeralloc]init];
//設置大小
maskLayer.frame = imageView.bounds;
//設置圖形樣子
maskLayer.path = maskPath.CGPath;
imageView.layer.mask = maskLayer;
[self.view addSubview:imageView];}
這三種方法中第三種最好,對內存的消耗最少啊,而且渲染快速。