iOSUIImage剪切圆形

王朝学院·作者佚名  2016-08-27  
宽屏版  字体: 小 | 中 | 大 | 超大  

//.h文件

#import <UIKit/UIKit.h>

@interface UIImage (XG)

/**

* @param icon 头像图片名称

* @param borderImage 边框的图片名称

* @param border 边框大小

*

* @return 圆形的头像图片

*/

+ (instancetype)imageWithIconName:(NSString *)icon borderImage:(NSString *)borderImage border:(int)border;

@end

//.m文件

#import "UIImage+XG.h"

@implementation UIImage (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)];

//设置头像frame

CGFloat 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();

return iconImage;

}

@end

borderImage 是边框 不需要的话给nil就可以

border 是边框宽度 不需要的话给0就行了

UIImage * image = [UIImage imageWithIconName:@"头像.png" borderImage:nil border:0];

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有