iOS圆角优化二种方案和特定圆角设置
2018-08-27 本文已影响116人
木马不在转
在APP开发中,圆角图片还是经常出现的。如果一个界面中只有少量圆角图片或许对性能没有非常大的影响,但是当圆角图片比较多的时候就会APP性能产生明显的影响,也就是离屏渲染。这会给我们带来额外的性能损耗,如果这样的圆角操作达到一定数量,会触发缓冲区的频繁合并和上下文的的频繁切换,性能的代价会宏观地表现在用户体验上——掉帧。
一:使用贝塞尔曲线UIBezierPath和Core Graphics框架画出一个圆角
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"myImg"];
//开始对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];
二:使用CAShapeLayer和UIBezierPath设置圆角
UIImageView *imageView = [[UIImageViewalloc] initWithFrame:CGRectMake(100,100,100,100)];
imageView.image = [UIImage imageNamed:@"myImg"];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.boundsbyRoundingCorners:UIRectCornerAllCornerscornerRadii:imageView.bounds.size];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
//设置大小
maskLayer.frame = imageView.bounds;
//设置图形样子
maskLayer.path = maskPath.CGPath;
imageView.layer.mask = maskLayer;
[self.view addSubview:imageView];
用CAShapeLayer的内存消耗少,渲染速度快,建议使用优化方案2。
二:设置某个圆角
//设置切哪个直角
// UIRectCornerTopLeft = 1 << 0, 左上角
// UIRectCornerTopRight = 1 << 1, 右上角
// UIRectCornerBottomLeft = 1 << 2, 左下角
// UIRectCornerBottomRight = 1 << 3, 右下角
// UIRectCornerAllCorners = ~0UL 全部角
//得到view的遮罩路径
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_backImageView.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10,10)];
//创建 layer
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = _backImageView.bounds;
//赋值
maskLayer.path = maskPath.CGPath;
_backImageView.layer.mask = maskLayer;