ios 将矩形图片裁剪成圆形图片

  在ios中将一个正方形的图片裁剪成圆形的图片是一件非常容易的事情, 直接设置 imageView.layer.cornerRadius 这个属性, 再设置 imageView.clipsToBounds = YES 就可以了, 但是对于长方形的图片来说这个方式裁剪出来的就不是一个圆形的了, 而是个椭圆的. 解决这个问题就需要自己画 并且需要计算. 最终效果图如下:

 

tips: 如果是裁剪矩形的话, 是从图片中心的位置为圆心剪裁的.

 

代码如下:

@implementation UIImage (CF)

 

+ (UIImage*)circleImageWith: (NSString*)imageName borderWidth: (CGFloat)width borderColor: (UIColor*)color

 

{   

  UIImage* oldImage = [UIImage imageNamed:imageName];

    

    CGFloat minLength  = MIN(oldImage.size.width, oldImage.size.height);

    CGFloat length = minLength + width * 2;

    CGFloat centerX = length * 0.5;

    CGFloat centerY = length * 0.5;

    CGFloat bigRadius = length * 0.5;

    

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(length, length), NO, 0.0);

    

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // 画大圆

    [color set];

    CGContextAddArc(ctx, centerX, centerY, bigRadius, 0, M_PI * 2, 0);

    

    CGContextFillPath(ctx);

    

    // 画小圆

    CGFloat smallRadius = minLength * 0.5;

    CGContextAddArc(ctx, centerX, centerY, smallRadius, 0, M_PI * 2, 0);

    CGContextClip(ctx);

    

    CGFloat imageX = centerX - oldImage.size.width * 0.5;

    CGFloat imageY = centerY - oldImage.size.height * 0.5;

    [oldImage drawInRect:CGRectMake(imageX, imageY, oldImage.size.width, oldImage.size.height)];

    

    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

    

    UIGraphicsEndImageContext();

    

    return newImage;

}

 

 

@end

 

转载于:https://www.cnblogs.com/yuchuanfeng/p/4825748.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值