iOS-图片剪裁

//1、加载旧图片
    UIImage *oldImage = [UIImage imageNamed:@"阿狸头像"];
    //2、创建上下文
    UIGraphicsBeginImageContextWithOptions(oldImage.size, NO, 0.0);
    //3、画圆正切于上下文
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, oldImage.size.width, oldImage.size.height)];
    //4、将路径设置为裁剪区
    [path addClip];
    //5、画图片
    [oldImage drawAtPoint:CGPointZero];
    //6、生成一个新的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    //7、关闭上下文
    UIGraphicsEndImageContext();
    //8、设置新图片
    self.imageView.image = newImage;

带圆环的图片剪裁(头像)

//1、设置圆环的宽度
    CGFloat boardW = 5;
    //2、加载旧图片
    UIImage *oldImage = [UIImage imageNamed:@"阿狸头像"];
    //3、新的图片尺寸
    CGFloat imageW = oldImage.size.width + 2 * boardW;
    CGFloat imageH = oldImage.size.height + 2 * boardW;
    //4、圆的半径
    CGFloat circirW = imageW > imageH ? imageH : imageW;
    //5、开启上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(circirW, circirW), NO, 0.0);
    //6、画大圆
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, circirW, circirW)];
    //7、获取当前上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //8、添加到上下文
    CGContextAddPath(ctx, path.CGPath);
    [[UIColor redColor] set];
    //9、渲染
    CGContextFillPath(ctx);
    //10、设置内圆尺寸
    CGRect clipR = CGRectMake(boardW, boardW, oldImage.size.width, oldImage.size.height);
    //11、画圆:正切旧图片的圆
    UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:clipR];
    //12、设置裁剪区域
    [clipPath addClip];
    //13、画圆片
    [oldImage drawAtPoint:CGPointMake(boardW, boardW)];
    //14、获取新图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    //15、关闭上下文
    self.imageView.image = newImage;

你可能感兴趣的:(iOS-图片剪裁)