有時候我們的應用需要登錄,登錄后的用戶信息中有用戶頭像,以前使用的方形圖片比較丑陋,現在基本所有的應用都是使用圓形都頭像了,但是用戶上傳上來都圖片不一定是圓形的(基本上都不是),這個時候就需要我們程序員來處理這些圖片了,處理的方法有兩種(根據需求),第一種是只要普通顏色的邊框(無邊框也可以)且圓形的頭像、第二種是需要花紋或者其他圖片的邊框 且 圓形的頭像。
以下為學習者提供的文章,不能用於商業利益。
一 、普通顏色的邊框(無邊框也可以)且圓形的頭像
代碼:
UIImage * image = [UIImage imageNamed:@"icon_huo"]; UIImageView * imageV = self.imageView; imageV.layer.masksToBounds = YES; imageV.layer.cornerRadius =imageV.frame.size.width / 2 ; /**如果需要邊框,請把下面2行注釋打開*/ // imageV.layer.borderColor = [UIColor purpleColor].CGColor; // imageV.layer.borderWidth = 10; imageV.image= image;

二、花紋或者其他圖片的邊框
為了更好的開發,把制作圓形的頭像功能封裝起來,首先為UIIamge新建一個Gategory(分類)
UIImage+XG.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
UIImage+XG.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
效果:
在需要制作圓形頭像或圖片的地方導入 #import "UIImage+XG.h"
UIImage * image = [UIImage imageWithIconName:@"icon_huo" borderImage:@"border" border:40]; self.imageView.image= image;
