第一種方法:通過設(shè)置layer的屬性
最簡單的一種,但是很影響性能,一般在正常的開發(fā)中使用很少.
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
//只需要設(shè)置layer層的兩個屬性
//設(shè)置圓角
imageView.layer.cornerRadius = imageView.frame.size.width / 2;
//將多余的部分切掉
imageView.layer.masksToBounds = YES;
[self.view addSubview:imageView];
第二種方法:使用Core Graphics框架畫出一個圓角
@interface UIImage(YYPClip)
- (UIImage *)drawCircleImage;
@end
@implementation UIImage(YYPClip)
- (UIImage *)drawCircleImage {
CGFloat side = MIN(self.size.width, self.size.height);
UIGraphicsBeginImageContextWithOptions(CGSizeMake(side, side), false, [UIScreen mainScreen].scale);
CGContextAddPath(UIGraphicsGetCurrentContext(),
[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, side, side)].CGPath);
CGContextClip(UIGraphicsGetCurrentContext());
CGFloat X = -(self.size.width - side) / 2.f;
CGFloat Y = -(self.size.height - side) / 2.f;
[self drawInRect:CGRectMake(X, Y, self.size.width, self.size.height)];
CGContextDrawPath(UIGraphicsGetCurrentContext(), kCGPathFillStroke);
UIImage *output = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return output;
}
@end
//在需要圓角時調(diào)用如下
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *img = [[UIImage imageNamed:@"order"] drawCircleImage];
dispatch_async(dispatch_get_main_queue(), ^{
view.image = img;
});
});
第三種方法:使用CAShapeLayer和UIBezierPath設(shè)置圓角
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"1"];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:imageView.bounds.size];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
//設(shè)置大小
maskLayer.frame = imageView.bounds;
//設(shè)置圖形樣子
maskLayer.path = maskPath.CGPath;
imageView.layer.mask = maskLayer;
[self.view addSubview:imageView];
以上三種方法來自簡書鏈接 http://www.itdecent.cn/p/e97348f42276
這個鏈接的文章里說第三種方法最好 對內(nèi)存消耗最少,可是在另一篇比較權(quán)威的文章http://www.itdecent.cn/p/57e2ec17585b 《iOS-離屏渲染詳解》里說第三種方法會使用到mask屬性,會離屏渲染,不僅這樣,還曾加了一個 CAShapLayer對象.著實(shí)不可以取。并指出第二種方法比較可取。另外還提出了第四種方法。
第四種方法:使用帶圓形的透明圖片.(需要UI做一個切圖)
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"美國1.jpeg"];
UIImageView *imageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView1.image = [UIImage imageNamed:@"圓形白邊中空圖"];
[self.view addSubview:imageView];
[self.view addSubview:imageView1];
最好最好的方法應(yīng)該是第四種了,雖然比較笨, 但是不會引發(fā)離屏渲染,對內(nèi)存消耗會比較小。
更新:SDWebImage中提供了切圓角圖片的方法,在UIImage + Transform類別里
- (nullable UIImage *)sd_roundedCornerImageWithRadius:(CGFloat)cornerRadius
corners:(SDRectCorner)corners
borderWidth:(CGFloat)borderWidth
borderColor:(nullable UIColor *)borderColor;