ios 裁剪圆形头像_iOS如何将图片裁剪成圆形

本文实例为大家分享了iOS将图片裁剪成圆形的具体代码,供大家参考,具体内容如下

原图:

圆形图片裁剪效果:

裁剪成带边框的圆形图片:

核心代码:

#import

@interface UIImage (image)

/**

* 生成一张圆形图片

*

* @param image 要裁剪的图片

*

* @return 生成的圆形图片

*/

+ (UIImage *)imageWithClipImage:(UIImage *)image;

/**

* 生成一张带有边框的圆形图片

*

* @param borderW 边框宽度

* @param borderColor 边框颜色

* @param image 要添加边框的图片

*

* @return 生成的带有边框的圆形图片

*/

+ (UIImage *)imageWithBorder:(CGFloat)borderW color:(UIColor *)borderColor image:(UIImage *)image;

@end

#import "UIImage+image.h"

@implementation UIImage (image)

+ (UIImage *)imageWithClipImage:(UIImage *)image{

+

//1.开启跟原始图片一样大小的上下文

UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);

//2.设置一个圆形裁剪区域

//2.1绘制一个圆形

UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)];

//2.2.把圆形的路径设置成裁剪区域

[path addClip];//超过裁剪区域以外的内容都给裁剪掉

//3.把图片绘制到上下文当中(超过裁剪区域以外的内容都给裁剪掉)

[image drawAtPoint:CGPointZero];

//4.从上下文当中取出图片

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

//5.关闭上下文

UIGraphicsEndImageContext();

return newImage;

}

+ (UIImage *)imageWithBorder:(CGFloat)borderW color:(UIColor *)borderColor image:(UIImage *)image{

//1.开启一个上下文

CGSize size = CGSizeMake(image.size.width + 2 * borderW, image.size.height + 2 * borderW);

UIGraphicsBeginImageContextWithOptions(size, NO, 0);

//2.绘制大圆,显示出来

UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];

[borderColor set];

[path fill];

//3.绘制一个小圆,把小圆设置成裁剪区域

UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];

[clipPath addClip];

//4.把图片绘制到上下文当中

[image drawAtPoint:CGPointMake(borderW, borderW)];

//5.从上下文当中取出图片

UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

//6.关闭上下文

UIGraphicsEndImageContext();

return newImage;

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

时间: 2020-02-22

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值