裁剪图片
===
- 1.开启上下文
objc:UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale)
- 2.获取上下文
objc:CGContextRef ref =UIGraphicsGetCurrentContext();
- 3.绘制裁剪区域
objc:CGContextAddEllipseInRect(CGContextRef __nullable c, CGRect rect);
- 4.将裁剪区域绘制在上下文中
objc:void CGContextClip(CGContextRef __nullable c);
- 5.将图片绘制在上下文中
objc:drawInRect:(CGRect)rect
- 6.拿到裁剪后的图片
objc:
UIImage* UIGraphicsGetImageFromCurrentImageContext(void)
- 7.关闭上下文
objc:void UIGraphicsEndImageContext(void)
code示例:要求,裁剪一个正方形图片为直径为边长的圆形图片,常用在 App 中用户的头像中
如图: —>
UIImage * image = [[UIImage alloc]init];//需要裁剪的图片,假设创建时已经是正方形有一定尺寸的图片。
// NO代表透明
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0);
// 获得上下文
CGContextRef ref = UIGraphicsGetCurrentContext();
// 添加一个椭圆(但这里其实画出来是个圆)
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
CGContextAddEllipseInRect(ref, rect);
// 裁剪
CGContextClip(ctx);
// 将图片画上去
[image drawInRect:rect];
// 拿到裁剪后的图片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
// 关闭上下文
UIGraphicsEndImageContext();