iOS中圓形圖片設(shè)置

現(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"];


結(jié)果

希望對大家有所幫助,如果有錯誤,請望指出,共同改正。

Demo地址:?圖片切圓Demo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容