头像添加边框

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

代码:

1.UIImage * image = [UIImage imageNamed:@'icon_huo'];
2.UIImageView * imageV = self.imageView;
3.imageV.layer.masksToBounds = YES;
4.imageV.layer.cornerRadius =imageV.frame.size.width / 2 ;
5./**如果需要边框,请把下面2行注释去掉*/
6.//    imageV.layer.borderColor = [UIColor purpleColor].CGColor;
7.//    imageV.layer.borderWidth = 10;
8.imageV.image=  image;

  

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

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

1.<strong>UIImage+XG.h 文件
2.</strong>
01.#import <UIKit/UIKit.h>
02. 
03.@interface UIImage (XG)
04. 
05./**
06.*  @param icon         头像图片名称
07.*  @param borderImage  边框的图片名称
08.*  @param border       边框大小
09.*
10.*  @return 圆形的头像图片
11.*/
12.+ (instancetype)imageWithIconName:(NSString *)icon borderImage:(NSString *)borderImage border:(int)border;
13.@end
1.<strong>UIImage+XG.m 文件
2.</strong>
01.#import 'UIImage+XG.h'
02. 
03.@implementation UIImage (XG)
04. 
05.+ (instancetype)imageWithIconName:(NSString *)icon borderImage:(NSString *)borderImage border:(int)border{
06.//头像图片
07.UIImage * image = [UIImage imageNamed:icon];
08.//边框图片
09.UIImage * borderImg = [UIImage imageNamed:borderImage];
10.//
11.CGSize size = CGSizeMake(image.size.width + border, image.size.height + border);
12. 
13.//创建图片上下文
14.UIGraphicsBeginImageContextWithOptions(size, NO, 0);
15. 
16.//绘制边框的圆
17.CGContextRef context = UIGraphicsGetCurrentContext();
18.CGContextAddEllipseInRect(context, CGRectMake(0, 0, size.width, size.height));
19. 
20.//剪切可视范围
21.CGContextClip(context);
22. 
23.//绘制边框图片
24.[borderImg drawInRect:CGRectMake(0, 0, size.width, size.height)];
25. 
26.//设置头像frame
27.CGFloat iconX = border / 2;
28.CGFloat iconY = border / 2;
29.CGFloat iconW = image.size.width;
30.CGFloat iconH = image.size.height;
31. 
32.//绘制圆形头像范围
33.CGContextAddEllipseInRect(context, CGRectMake(iconX, iconY, iconW, iconH));
34. 
35.//剪切可视范围
36.CGContextClip(context);
37. 
38.//绘制头像
39.[image drawInRect:CGRectMake(iconX, iconY, iconW, iconH)];
40. 
41.//取出整个图片上下文的图片
42.UIImage *iconImage = UIGraphicsGetImageFromCurrentImageContext();
43. 
44.return iconImage;
45.}
46.@end

效果:

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

1.UIImage * image = [UIImage imageWithIconName:@'icon_huo' borderImage:@'border' border:40];
2. 
3.self.imageView.image=  image;
posted @ 2016-04-15 16:13  橘子与布丁  阅读(1446)  评论(0编辑  收藏  举报