现在APP应用中,圆形图片的设置越来越多,下面就来分享我的设置圆形图片的经验。
1.不采用的方法
UIImageView*newImageView = [[UIImageViewalloc]initWithFrame:CGRectMake(100, 100, 72, 72)];
newImageView.backgroundColor= [UIColorgreenColor];
[self.viewaddSubview:newImageView];
self.imageView.image= [UIImageimageNamed:@"ic_8"];
self.imageView.layer.cornerRadius= 25;
self.imageView.layer.masksToBounds=YES;
这种方法设置一两张(图片数量较少情况下)可以使用,如果设置图片的数量比较多,再使用这种方法就不太好了(例如:微博首页界面展示的信息, 每一个好友头像都需要设置圆形图片)。
2.采用的方法
我们使用 cocoas2D 处理圆形图片,示例代码如下:
1.首先创建一个 UIImage 的类别
#import"UIImage+Exction.h"
@implementationUIImage (Exction)
- (UIImage*)circleImage {
//开启图片上下文
UIGraphicsBeginImageContextWithOptions(self.size,NO, 0.0);
//获得上下文
CGContextRefctx =UIGraphicsGetCurrentContext();
//添加一个圆
CGRectrect =CGRectMake(0, 0,self.size.width,self.size.height);
CGContextAddEllipseInRect(ctx, rect);
//剪接
CGContextClip(ctx);
//将图片画上去
[selfdrawInRect:rect];
//得到图片
UIImage*image =UIGraphicsGetImageFromCurrentImageContext();
//结束图片上下文
UIGraphicsEndImageContext();
returnimage;
}
@end
2.创建一个 UIImageView 的类别
#import"UIImageView+Exction.h"
#import"UIImage+Exction.h"
#import"UIImageView+WebCache.h"
@implementationUIImageView (Exction)
- (void)setHeaher:(NSString*)url {
UIImage*imageDef = [[UIImageimageNamed:@"ic_8"]circleImage];
[selfsd_setImageWithURL:[NSURLURLWithString:url]placeholderImage:imageDef completed:^(UIImage*image, NSError*error,SDImageCacheTypecacheType,NSURL*imageURL) {
self.image= image ? [imagecircleImage] : imageDef;
}];
}
@end
3.结果展示
在控制器中为 UIImageView 赋值
[self.imageView setHeaher:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1511682048280&di=40aa097098ab81da2c309cbd98081df5&imgtype=0&src=http%3A%2F%2Fimg2.3lian.com%2F2014%2Ff3%2F71%2Fd%2F1.jpg"];
希望对大家有所帮助,如果有错误,请望指出,共同改正。
Demo地址: 图片切圆Demo