有時候需要快速的創建一些圓形的UIView,UIButton之類的,如果有時間自己封裝控件,使用CG繪製當然很好,但是如果沒有時間,那麼就使用CALayer的特性來做吧。
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
//只需要設置layer層的兩個屬性
//設置圓角
imageView.layer.cornerRadius = imageView.frame.size.width / 2;
//將多餘的部分切掉
imageView.layer.masksToBounds = YES;
[self.view addSubview:imageView];
----------------------------------------------------------------------------------------------------------------------------------------------------------------
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"1"];
//開始對imageView進行畫圖
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, [UIScreen mainScreen].scale);
//使用貝塞爾曲線畫出一個圓形圖
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:imageView.frame.size.width] addClip];
[imageView drawRect:imageView.bounds];
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
//結束畫圖
UIGraphicsEndImageContext();
[self.view addSubview:imageView];
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
第三種方法,性能最好寫,記得導入<AVFoundation/AVFoundation.h>
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"1"];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:imageView.bounds.size];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
//設置大小
maskLayer.frame = imageView.bounds;
//設置圖形樣子
maskLayer.path = maskPath.CGPath;
imageView.layer.mask = maskLayer;
[self.view addSubview:imageView];
}
這三種方法中第三種最好,對內存的消耗最少啊,而且渲染快速。