UIImageView 圆角
2018-08-27 本文已影响4人
白色天空729
OC 版本:
创建UIImageView 分类:
xxx.m
@implementation UIImage (ImageCIr)
/** 设置圆形图片(放到分类中使用) */
+ (nullable UIImage *)clipCircleImageWithImage:(nullable UIImage *)image circleRect:(CGRect)rect {
//1、开启上下文
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
//2、设置裁剪区域
UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect:rect];
[path addClip];
//3、绘制图片
[image drawAtPoint:CGPointZero];
//4、获取新图片
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
//5、关闭上下文
UIGraphicsEndImageContext();
//6、返回新图片
return newImage;
}
xxx.h
+ (nullable UIImage *)clipCircleImageWithImage:(nullable UIImage *)image circleRect:(CGRect)rect;
使用:
UIImageView *roundImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, 200, 200)];
UIImage *image = [UIImage imageNamed:@"zzz"];
roundImg.image = [UIImage clipCircleImageWithImage:image circleRect:roundImg.frame];
[self.view addSubview:roundImg];
Swift版本:
extension UIImageView {
/// 图片切成圆形
///
/// - Parameters:
/// - image: 传入处理的图片
/// - rect: 切割的大小
/// - Returns: 返回切割的t圆形图片
func clipCircleImage(with image: UIImage?, circleRect rect: CGRect) -> UIImage? {
//1、开启上下文
UIGraphicsBeginImageContextWithOptions(image?.size ?? CGSize.zero, false, 0)
//2、设置裁剪区域
let path = UIBezierPath(ovalIn: rect)
path.addClip()
//3、绘制图片
image?.draw(at: CGPoint.zero)
//4、获取新图片
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
//5、关闭上下文
UIGraphicsEndImageContext()
//6、返回新图片
return newImage
}
}
调用:
let img = UIImageView.init(frame: CGRect.init(x: 0, y: 64, width: 200, height: 200))
let customImg = UIImage.init(named: "aaa")
img.image = img.clipCircleImage(with: customImg, circleRect: CGRect(x: 0, y: 0, width: img.frame.width, height: img.frame.height))
view.addSubview(img)