异步绘制圆角图片

next 颜色,边框

  • 如何调用
    block作为参数的参数

  • 绘制圆角图片
    • 开启图形上下文 UIGraphicsBeginImageContext(<#CGSize size#>)
    • 从上下文中获得图片UIGraphicsGetImageFromCurrentImageContext();
    • 关闭上下文 UIGraphicsEndImageContext();
  • 混合模式Color Blended Layers
  • 多线程后台执行耗时操作
  • 利用block把结果返回给调用方

使用异步调用代码

UIImage *image = [UIImage imageNamed:@"avater"];
[image mg_cornerImageWithSize:_imageView.bounds.size fillColor:[UIColor whiteColor] completion:^(UIImage *image) {
    imageView.image = image;
}];

异步绘制圆角图片

@implementation UIImage (Extension)
- (void)mg_cornerImageWithSize:(CGSize)size fillColor:(UIColor *)fillColor completion:(void (^)(UIImage *image))completion
{   
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 耗时操作
        // 开启图形上下文
        UIGraphicsBeginImageContextWithOptions(size, YES, 0);
        CGRect rect = CGRectMake(0, 0, size.width, size.height);
        
        // 设置背景填充颜色
        [fillColor setFill];
        UIRectFill(rect);
        
        // Bezier绘制图形
        UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect];
        [path addClip];
        [self drawInRect:rect];
        
        // 获得结果
        UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
        
        // 关闭
        UIGraphicsEndImageContext();
        
        // 到主线程中刷新UI, 完成回调
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completion != nil) {
                completion(result);
            }
        });
    });
}
@end
普通绘制圆角图片
@implementation UIImage (Extension)
- (instancetype)circleImage
{
    UIGraphicsBeginImageContext(self.size);
    // NO代表透明
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    // 获得上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 画圆
    CGRect rect = {CGPointZero, self.size};
    CGContextAddEllipseInRect(context, rect);

    // 裁剪
    CGContextClip(context);
    // 将下载好的图片画到圆上
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // 关闭上下文
    UIGraphicsEndImageContext();

    return image;
}
@implementation UIImage (Extension)

CAShapeLayer

cornerRadius和maskToBounds独立作用的时候都不会有太大的性能问题,但是当他俩结合在一起,就触发了屏幕外渲染。有时候你想显示圆角并沿着图层裁切子图层的时候,你可能会发现你并不需要沿着圆角裁切,这个情况下用CAShapeLayer就可以避免这个问题了。

你想要的只是圆角且沿着矩形边界裁切,同时还不希望引起性能问题。
其实你可以用现成的UIBezierPath的构造器
`+bezierPathWithRoundedRect:cornerRadius:`
这样做并不会比直接用`cornerRadius`更快,但是它避免了性能问题

参考资料

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容