1.直接设置Layer
示例代码:
- (void)demo1 {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
imageView.center = self.view.center;
[self.view addSubview:imageView];
imageView.image = [UIImage imageNamed:@"111.png"];
imageView.layer.cornerRadius = imageView.frame.size.height * 0.5;
imageView.layer.masksToBounds = YES;
}
缺点:性能不是很好的方法,不适合在tableview中使用
这种方式会强制 Core Animation 提前渲染屏幕的离屏绘制, 而离屏绘制就会给性能带来负面影响,甚至会有卡顿的现象出现
2.使用绘图上下文的方式绘制圆角
示例代码:
- (void)demo2 {
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
imageView.center = self.view.center;
[self.view addSubview:imageView];
UIColor *color = self.view.backgroundColor;
UIImage *image = [UIImage imageNamed:@"111.png"];
/*
开启图形上下文(bitmap类型)
参数1:尺寸
参数2:是否不透明
参数3:缩放比 0->当前屏幕缩放比
*/
UIGraphicsBeginImageContextWithOptions(imageView.frame.size, YES, 0);
//设置填充颜色
[color setFill];
UIRectFill(imageView.bounds);
//使用贝塞尔曲线给图片切割
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:imageView.bounds];
[path addClip];
[image drawInRect:imageView.bounds];
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imageView.image = resultImage;
}
注意:在填充图片前完成路径切割,如果提前填充图片再切割不会有效果
3.使用分类的方式绘图
- (void)demo3 {
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
imageView.center = self.view.center;
[self.view addSubview:imageView];
UIImage *image = [UIImage imageNamed:@"111.png"];
[image lv_cornerImageWithSize:imageView.bounds.size fillColor:[UIColor whiteColor] completion:^(UIImage *image) {
imageView.image = image;
}];
}
分类代码:
.h
#import <UIKit/UIKit.h>
@interface UIImage (Extension)
- (void)lv_cornerImageWithSize:(CGSize)size fillColor:(UIColor *)fillColor completion:(void (^)(UIImage *image))completion;
@end
.m
#import "UIImage+Extension.h"
@implementation UIImage (Extension)
- (void)lv_cornerImageWithSize:(CGSize)size fillColor:(UIColor *)fillColor completion:(void (^)(UIImage *))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);
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect];
[path addClip];
[self drawInRect:rect];
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
//关闭上下文
UIGraphicsEndImageContext();
dispatch_async(dispatch_get_main_queue(), ^{
if (completion) {
completion(resultImage);
}
});
});
}
@end