現(xiàn)在APP應(yīng)用中,圓形圖片的設(shè)置越來越多,下面就來分享我的設(shè)置圓形圖片的經(jīng)驗。
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;
這種方法設(shè)置一兩張(圖片數(shù)量較少情況下)可以使用,如果設(shè)置圖片的數(shù)量比較多,再使用這種方法就不太好了(例如:微博首頁界面展示的信息, 每一個好友頭像都需要設(shè)置圓形圖片)。

2.采用的方法
我們使用?cocoas2D?處理圓形圖片,示例代碼如下:
1.首先創(chuàng)建一個 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();
//結(jié)束圖片上下文
UIGraphicsEndImageContext();
returnimage;
}
@end
2.創(chuàng)建一個 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.結(jié)果展示
在控制器中為 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