方式一:
_imageView.image = [UIImage imageNamed:@"pic"];
_imageView.layer.cornerRadius = _imageView.frame.size.width/2;
_imageView.layer.masksToBounds = YES;
這種方式不建議使用,因為使用圖層過量,特別是弄圓角或者陰影會很卡,設置圖片圓角一般采用繪圖來做。如下
方式二:
定義一個UIImage
的分類,將方法寫進該分類:
#import <UIKit/UIKit.h>
@interface UIImage (shape)
- (UIImage *)cutCircleImage;
@end
#import "UIImage+shape.h"
@implementation UIImage (shape)
/** 設置圓形圖片(放到分類中使用) */
- (UIImage *)cutCircleImage{
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
// 獲取上下文
CGContextRef ctr = UIGraphicsGetCurrentContext();
// 設置圓形
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextAddEllipseInRect(ctr, rect);
// 裁剪
CGContextClip(ctr);
// 將圖片畫上去
[self drawInRect:rect];
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultImage;
}
調用該方法:
_imageView.image = [[UIImage imageNamed:@"pic"] cutCircleImage];