图片剪裁

本文介绍了一种使用iOS技术将图片裁剪成圆形的方法,并详细解释了如何通过UIBezierPath和其他UIKit框架组件来实现这一效果。
  • (void)clipCircle
    {
    // 圆环的宽度
    CGFloat borderW = 5;
    // 加载旧的图片
    UIImage *oldImage = [UIImage imageNamed:@”阿狸头像”];
    // 新的图片尺寸
    CGFloat imageW = oldImage.size.width + 2 * borderW;
    CGFloat imageH = oldImage.size.height + 2 * borderW;
    // 设置新的图片尺寸
    CGFloat circirW = imageW > imageH ? imageH : imageW;
    // 开启上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(circirW, circirW), NO, 0.0);
    // 画大圆
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, circirW, circirW)];
    // 获取当前上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    // 添加到上下文
    CGContextAddPath(ctx, path.CGPath);
    [[UIColor whiteColor] set];
    // 渲染
    CGContextFillPath(ctx);
    CGRect clipR = CGRectMake(borderW, borderW, oldImage.size.width, oldImage.size.height);
    // 画圆:正切于旧图片的圆
    UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:clipR];
    // 设置裁剪区域
    [clipPath addClip];
    // 画图片
    [oldImage drawAtPoint:CGPointMake(borderW, borderW)];
    // 获取新的图片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭上下文
    UIGraphicsEndImageContext();
    _imageView.image = newImage;
    }

  • (void)clip
    {
    // 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();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值