您的位置:首页 > 其它

头像添加边框

2016-04-15 16:13 543 查看
一 、普通颜色的边框(无边框也可以)且圆形的头像

代码:

view sourceprint?

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(分类)

view sourceprint?

1.
<strong>UIImage+XG.h 文件

2.
</strong>


view sourceprint?

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


view sourceprint?

1.
<strong>UIImage+XG.m 文件

2.
</strong>


view sourceprint?

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


view sourceprint?

1.


效果:


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

view sourceprint?

1.


view sourceprint?

1.
UIImage * image = [UIImage imageWithIconName:@
'icon_huo'
borderImage:@
'border'
border:
40
];

2.

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