//.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];
新聞熱點
疑難解答