您的位置:首页 > 产品设计 > UI/UE

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

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

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

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

代码:

UIImage*image=[UIImageimageNamed:@"icon_huo"];
UIImageView*imageV=self.imageView;
imageV.layer.masksToBounds=YES;
imageV.layer.cornerRadius=imageV.frame.size.width/2;
/**如果需要边框,请把下面2行注释去掉*/
//imageV.layer.borderColor=[UIColorpurpleColor].CGColor;
//imageV.layer.borderWidth=10;
imageV.image=image;






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

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

UIImage+XG.h文件


#import<UIKit/UIKit.h>

@interfaceUIImage(XG)

/**
*@paramicon头像图片名称
*@paramborderImage边框的图片名称
*@paramborder边框大小
*
*@return圆形的头像图片
*/
+(instancetype)imageWithIconName:(NSString*)iconborderImage:(NSString*)borderImageborder:(int)border;
@end


UIImage+XG.m文件


#import"UIImage+XG.h"

@implementationUIImage(XG)

+(instancetype)imageWithIconName:(NSString*)iconborderImage:(NSString*)borderImageborder:(int)border{
//头像图片
UIImage*image=[UIImageimageNamed:icon];
//边框图片
UIImage*borderImg=[UIImageimageNamed:borderImage];
//
CGSizesize=CGSizeMake(image.size.width+border,image.size.height+border);

//创建图片上下文
UIGraphicsBeginImageContextWithOptions(size,NO,0);

//绘制边框的圆
CGContextRefcontext=UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(context,CGRectMake(0,0,size.width,size.height));

//剪切可视范围
CGContextClip(context);

//绘制边框图片
[borderImgdrawInRect:CGRectMake(0,0,size.width,size.height)];

//设置头像frame
CGFloaticonX=border/2;
CGFloaticonY=border/2;
CGFloaticonW=image.size.width;
CGFloaticonH=image.size.height;

//绘制圆形头像范围
CGContextAddEllipseInRect(context,CGRectMake(iconX,iconY,iconW,iconH));

//剪切可视范围
CGContextClip(context);

//绘制头像
[imagedrawInRect:CGRectMake(iconX,iconY,iconW,iconH)];

//取出整个图片上下文的图片
UIImage*iconImage=UIGraphicsGetImageFromCurrentImageContext();

returniconImage;
}
@end



效果:


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



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

self.imageView.image=image;





                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: