通过MaskView 来实现圆角功能
@implementation JH_CircleImageView
/*
* 两种情况:
* 第一种:先设置Frame =》设置image
这个时候 self.image = self.image,传入的是nil,直接给nil,不过这个时候Frame 已经知道了
这个时候 再绘制image 就可以知道半径是多少
* 第二种:先设置Image =》设置Frame
先保存Image,等Frame设置后再 绘制
但是有个缺点: 如果 再次改变Frame,那么 以为还是保留了 上次的圆角图的基础上再绘制圆角
**/
- (void)layoutSubviews {
[super layoutSubviews];
//已经获取了正确的宽高度 开始绘制半径图片
self.image = self.image;
}
- (void)setImage:(UIImage *)image {
__block UIImage * tmpImage = image;
/*
* 如果 imageView的 宽高为0
* 或者传过来的为nil
* 直接不用去绘制
**/
if (image == nil || CGRectGetWidth(self.frame) == 0|| CGRectGetHeight(self.frame) == 0) {
[super setImage:image];
} else {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
tmpImage.circleRadius = CGRectGetWidth(self.frame)/2.0;
tmpImage = [tmpImage drawCircleImage];
dispatch_async(dispatch_get_main_queue(), ^{
[super setImage:tmpImage];
});
});
}
}
@end
image 扩展
#import "UIImage+JH_Circle.h"
#import <objc/runtime.h>
static char CircleRadiusKey;
@implementation UIImage (JH_Circle)
- (UIImage *)drawCircleImage {
if (self.circleRadius <= 0) {
return nil;
}
UIGraphicsBeginImageContextWithOptions((CGSize){self.circleRadius*2,self.circleRadius*2}, NO, [UIScreen mainScreen].scale);
[[UIBezierPath bezierPathWithRoundedRect:(CGRect){0,0,self.circleRadius*2,self.circleRadius*2} cornerRadius:self.circleRadius] addClip];
[self drawInRect:(CGRect){0,0,self.circleRadius*2,self.circleRadius*2}];
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return outputImage;
}
- (void)setCircleRadius:(CGFloat)circleRadius {
objc_setAssociatedObject(self,&CircleRadiusKey,
@(circleRadius),
OBJC_ASSOCIATION_RETAIN);
}
- (CGFloat)circleRadius {
NSNumber * value = objc_getAssociatedObject(self, &CircleRadiusKey);
return value.floatValue;
}
@end