76-圆形裁剪(指定图片裁剪为圆形),添加UIImage分类,两个类方法,实现圆形裁剪

来源:互联网 发布:lodash 知乎 编辑:程序博客网 时间:2024/05/20 11:47

//  UIImage+cilcleImage.m
//  圆形裁剪,常用于设置头像

#import "UIImage+cilcleImage.h"

//UIImage添加分类,两个类方法,实现圆形裁剪
@implementation UIImage (cilcleImage)


/**
 *  
头像圆形裁剪(周围带圆环)
 *
 *  
@param borderWidth 圆环宽度
 *  
@param borderColor 圆环颜色
 *  
@param image       想要裁剪的图片
 *
 *  
@return 裁剪完成的图片
 */

+(
UIImage *) cilcleImageWithCilcleBorderWidth:(CGFloat) borderWidth borderColor:(UIColor *) borderColor image:(UIImage *)image
{
    
//UIImage *image=[UIImage imageNamed:@"阿狸头像"];
    
//设置大圆的rect
    
CGFloat w=image.size.width+2 *borderWidth;
    
CGFloat h=image.size.width+2 *borderWidth;
    
CGRect bigCirCleRect=CGRectMake(00, w, h);
    
    
//1.开启上下文
    
UIGraphicsBeginImageContextWithOptions(bigCirCleRect.sizeNO0);
    
    
//2.拼接路径
    
    
//2.1 绘制大圆
    
UIBezierPath *bigpath=[UIBezierPath bezierPathWithOvalInRect:bigCirCleRect];
    
//设置圆环颜色
    [borderColor 
set];
    
//填充圆环
    [bigpath 
fill];
    
    
//2.2 设置裁剪区域
    
CGRect clipRect=CGRectMake(borderWidth, borderWidth, image.size.width, image.size.height);
    
//2.3 描述裁剪区域路径
    
UIBezierPath *clipPath=[UIBezierPath bezierPathWithOvalInRect:clipRect];
    
//根据裁剪路径裁剪
    [clipPath 
addClip];
    
    
//3.绘制图片
    [image 
drawAtPoint:CGPointMake(borderWidth, borderWidth)];
    
    
//4.获取图片
    image=
UIGraphicsGetImageFromCurrentImageContext();
    
    
//5.关闭上下文
    
UIGraphicsEndImageContext();
    
    
return image;
}

/**
 *  
普通头像圆形裁剪
 *
 *  
@param image 想要裁剪的图片
 *
 *  
@return 裁剪完成的图片
 */

+(
UIImage *) circleImage:(UIImage *)image
{
    
//0.加载图片
    
//UIImage *img=[UIImage imageNamed:@"阿狸头像"];
    
    
//1.开启位图上下文
    
UIGraphicsBeginImageContextWithOptions(image.sizeNO0);
    
    
//2.设置裁剪区域(图片大小)
    
//默认只会影响到后面的东西,会把超出裁剪区域的范围裁剪掉
    
CGRect circeRect=CGRectMake(00, image.size.width, image.size.height);
    
    
//3.描述圆形路径
    
UIBezierPath *path=[UIBezierPath bezierPathWithOvalInRect:circeRect];
    
    
//4.根据圆形路径裁剪路径
    [path 
addClip];
    
    
//5.绘制图片
    [image 
drawAtPoint:CGPointZero];
    
    
//6.获取图片(把当前上下文转换成图片)
    image=
UIGraphicsGetImageFromCurrentImageContext();
    
    
//7.关闭上下文
    
UIGraphicsEndImageContext();
    
    
return image;
}

@end
0 0