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;
複製代碼
相關文章
相關標籤/搜索