iOS给imageView高效的添加圆角

清晨

  • 经常使用的解决方案
self.view.layer.cornerRadius = 5;
self.view.layer.masksToBounds = YES;
复制代码

使用上面的方式会强制Core Animation提早渲染屏幕的离屏绘制, 而离屏绘制就会给性能带来负面影响,会有卡顿的现象出现bash

  • 使用绘图技术 Core Graphics
- (UIImage *)circleImage {
    // NO表明透明
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    // 得到上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    // 添加一个圆
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextAddEllipseInRect(ctx, rect);
    // 裁剪
    CGContextClip(ctx);
    // 将图片画上去
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭上下文
    UIGraphicsEndImageContext();
    return image;
}
复制代码
  • 另一种实现圆角的方法,其实也是使用绘图技术实现的
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
imageView.center = CGPointMake(200, 300);
UIImage *anotherImage = [UIImage imageNamed:@"image"];
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds
                       cornerRadius:50] addClip];
[anotherImage drawInRect:imageView.bounds];
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.view addSubview:imageView];
复制代码
  • 使用layermask属性实现
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.coverImageView.bounds cornerRadius:2];
CAShapeLayer *maskLayer = [CAShapeLayer new];
maskLayer.frame = self.coverImageView.bounds;
maskLayer.path = maskPath.CGPath;
self.coverImageView.layer.mask = maskLayer;
复制代码