优化方案1:使用贝塞尔曲线UIBezierPath和Core Graphics框架画出一个圆角
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"about"];
//开始对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();
[self.view addSubview:imageView];
优化方案2:使用CAShapeLayer和UIBezierPath设置圆角
//圆角设置
- (void)getCircleCorner{
UIImageView *view = [[UIImageView alloc]initWithFrame:CGRectMake(100, 400, 100, 100)];
view.backgroundColor = [UIColor redColor];
[self.view addSubview:view];
/*
UIRectCornerTopLeft = 1 << 0,
UIRectCornerTopRight = 1 << 1,
UIRectCornerBottomLeft = 1 << 2,
UIRectCornerBottomRight = 1 << 3,
UIRectCornerAllCorners = ~0UL
*/
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectEdgeLeft | UIRectCornerBottomLeft cornerRadii:CGSizeMake(50, 50)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
maskLayer.frame = view.bounds;
maskLayer.path = path.CGPath;
view.layer.mask = maskLayer;
}
对于方案2需要解释的是:
CAShapeLayer继承于CALayer,可以使用CALayer的所有属性值;
CAShapeLayer需要贝塞尔曲线配合使用才有意义(也就是说才有效果)
使用CAShapeLayer(属于CoreAnimation)与贝塞尔曲线可以实现不在view的drawRect(继承于CoreGraphics走的是CPU,消耗的性能较大)方法中画出一些想要的图形
CAShapeLayer动画渲染直接提交到手机的GPU当中,相较于view的drawRect方法使用CPU渲染而言,其效率极高,能大大优化内存使用情况。