iOS剪切图片的三种方法

第一种方法:通过设置layer的属性

最简单的一种,但是很影响性能,一般在正常的开发中使用很少.

lable.clipsToBounds = YES;(耗内存)
lable.layer.cornerRadius = 50;

第二种方法:通过UIGraphics和贝塞尔曲线进行绘制

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 400, 100, 100)];
    imageView.image = [UIImage imageNamed:@"ask"];
    imageView.image = [self imageWithCornerRadius:50 withImageView:imageView];
    [self.view addSubview:imageView];

- (UIImage *)imageWithCornerRadius:(CGFloat)radius withImageView:(UIImageView *)imageView{
    CGRect rect = (CGRect){0.f, 0.f, imageView.frame.size};
    UIGraphicsBeginImageContextWithOptions(imageView.frame.size, NO, UIScreen.mainScreen.scale);
    CGContextAddPath(UIGraphicsGetCurrentContext(),[UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
    CGContextClip(UIGraphicsGetCurrentContext());
    
    [imageView.image drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
   
}

第三种方法:使用CAShapeLayer和UIBezierPath设置圆角

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    imageView.image = [UIImage imageNamed:@"1"];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:imageView.bounds.size];

    CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
    //设置大小
    maskLayer.frame = imageView.bounds;
    //设置图形样子
    maskLayer.path = maskPath.CGPath;
    imageView.layer.mask = maskLayer;
    [self.view addSubview:imageView];

你可能感兴趣的:(iOS剪切图片的三种方法)