iOS中圆形图片设置

现在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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容