美文网首页
iOS开发 --制作圆形的头像(UIImage)

iOS开发 --制作圆形的头像(UIImage)

作者: 探路者1202 | 来源:发表于2016-09-27 15:46 被阅读0次

有时候我们的应用需要登录,登录后的用户信息中有用户头像,以前使用的方形图片比较丑陋,现在基本所有的应用都是使用圆形都头像了,但是用户上传上来都图片不一定是圆形的(基本上都不是),这个时候就需要我们程序员来处理这些图片了,处理的方法有两种(根据需求),第一种是只要普通颜色的边框(无边框也可以)且圆形的头像、第二种是需要花纹或者其他图片的边框 且 圆形的头像。

以下为学习者提供的文章,不能用于商业利益。

一 、普通颜色的边框(无边框也可以)且圆形的头像

代码:

UIImage * image = [UIImage imageNamed:@"icon_huo"];

UIImageView* imageV =self.imageView;

imageV.layer.masksToBounds=YES;

imageV.layer.cornerRadius=imageV.frame.size.width /2;/**如果需要边框,请把下面2行注释去掉*///imageV.layer.borderColor = [UIColor purpleColor].CGColor;//imageV.layer.borderWidth = 10;imageV.image=  image;

二、花纹或者其他图片的边框

为了更好的开发,把制作圆形的头像功能封装起来,首先为UIIamge新建一个Gategory(分类)

UIImage+XG.h 文件

#import@interfaceUIImage (XG)/**

*  @param icon        头像图片名称

*  @param borderImage  边框的图片名称

*  @param border      边框大小

*

*  @return 圆形的头像图片*/+ (instancetype)imageWithIconName:(NSString *)icon borderImage:(NSString *)borderImage border:(int)border;@end

UIImage+XG.m 文件

#import"UIImage+XG.h"@implementationUIImage (XG)+ (instancetype)imageWithIconName:(NSString *)icon borderImage:(NSString *)borderImage border:(int)border{//头像图片UIImage * image =[UIImage imageNamed:icon];//边框图片UIImage * borderImg =[UIImage imageNamed:borderImage];//CGSize size = CGSizeMake(image.size.width + border, image.size.height +border);//创建图片上下文UIGraphicsBeginImageContextWithOptions(size, NO,0);//绘制边框的圆CGContextRef context =UIGraphicsGetCurrentContext();

CGContextAddEllipseInRect(context, CGRectMake(0,0, size.width, size.height));//剪切可视范围CGContextClip(context);//绘制边框图片[borderImg drawInRect:CGRectMake(0,0, size.width, size.height)];//设置头像frameCGFloat iconX = border /2;

CGFloat iconY= border /2;

CGFloat iconW=image.size.width;

CGFloat iconH=image.size.height;//绘制圆形头像范围CGContextAddEllipseInRect(context, CGRectMake(iconX, iconY, iconW, iconH));//剪切可视范围CGContextClip(context);//绘制头像[image drawInRect:CGRectMake(iconX, iconY, iconW, iconH)];//取出整个图片上下文的图片UIImage *iconImage =UIGraphicsGetImageFromCurrentImageContext();returniconImage;

}@end

效果:

在需要制作圆形头像或图片的地方导入   #import "UIImage+XG.h"

UIImage * image = [UIImage imageWithIconName:@"icon_huo"borderImage:@"border"border:40];

self.imageView.image=  image;

相关文章

网友评论

      本文标题:iOS开发 --制作圆形的头像(UIImage)

      本文链接:https://www.haomeiwen.com/subject/qxncyttx.html