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`更快,但是它避免了性能问题