iOS 顯示圓形頭像是一個比較常見的需求,之前面試的時候也有被問到。當(dāng)時答出來的是設(shè)置 CALayer 以及在 Storyboard 中設(shè)置,第二種沒有答出來?,F(xiàn)在把三種方法寫一下,效果圖如下:
CALayer
UIView 和 CALayer 的關(guān)系在這里不多說,CALayer 主要的作用是繪制。
目前假設(shè)一個 UIImageView 叫 avatarImageView,那么方法為:
// 設(shè)置 layer 以外的區(qū)域不顯示,默認(rèn)為 NO
avatarImageView.layer.masksToBounds = YES;
// 設(shè)置 layer 的圓角
avatarImageView.layer.cornerRadius = avatarImageView.bounds.size.height/2;
// 設(shè)置 layer 邊框顏色和寬度
avatarImageView.layer.borderWidth = 3.0;
avatarImageView.layer.borderColor = [UIColor whiteColor].CGColor;
Duartz2D
直接提供方法:
/**
獲取圓形圖片
@param originImage 原圖
@param borderWidth 邊框?qū)挾? @param borderColor 邊框顏色
@return 返回圓形圖片
*/
- (UIImage *)getRoundAvatar:(UIImage *)originImage borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor {
// 定義新圖片的尺寸
CGFloat bigImageWidth = originImage.size.width + 2 * borderWidth;
CGFloat bigImageHeight = originImage.size.height + 2 * borderWidth;
CGSize imageSize = CGSizeMake(bigImageWidth, bigImageHeight);
// 開啟上下文
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
// 取得當(dāng)前上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 設(shè)置邊框顏色
[borderColor set];
// 設(shè)置邊框
CGFloat bigRadius = bigImageWidth / 2.0;
CGFloat centerX = bigRadius;
CGFloat centerY = bigRadius;
CGContextAddArc(ctx, centerX, centerY, bigRadius, 0, M_PI * 2, 0);
CGContextFillPath(ctx);
// 設(shè)置小圓
CGFloat smallRadius = bigRadius - borderWidth;
CGContextAddArc(ctx, centerY, centerY, smallRadius, 0, M_PI * 2, 0);
// 裁剪
CGContextClip(ctx);
// 畫圖
[originImage drawInRect:CGRectMake(borderWidth, borderWidth, originImage.size.width, originImage.size.height)];
// 獲取新圖片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 結(jié)束上下文
UIGraphicsEndImageContext();
return newImage;
}
調(diào)用方式:
[avatarImageView setImage:[self getRoundAvatar:[UIImage imageNamed:@"somePic.jpg"]
borderWidth:3.0
borderColor:[UIColor whiteColor]]];
Storyboard / Xib 設(shè)置
在 Identity inspector 中的 User Defined Runtime Attribute 添加如下信息:
這里其實(shí)和 CALayer 的設(shè)置方法一致。
但是因為 border color 的類型為 CGColor ,所以在這里設(shè)置并不會起作用,會始終為黑色。
總結(jié)
Storyboard 的可維護(hù)性不是太強(qiáng),一般不推薦使用;
CALayer 方式的代碼比較簡單,并且有一定的靈活性;
Duartz2D 代碼比較高,但是可擴(kuò)展性很高。
Demo 地址:RoundAvatarDemo - Objective-C