在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