裁剪带圆环的圆形的图片步骤:spa
1.加载图片orm
UIImage *image = [UIImage imageNamed:@"dst2"];对象
2.开启图形上下文对象begin(后须要关闭end)图片
由于圆环上下文的size比图片大一些。ip
CGFloat margin = 5;get
CGSize ctxSize = CGSizeMake(image.size.width +2*margin , image.size.height + 2*margin);it
UIGraphicsBeginImageContextWithOptions(ctxSize, YES, 0);io
3.获取开启的上下文对象im
CGContextRef ctx = UIGraphicsGetCurrentContext();margin
4.肯定圆形的圆环的半径与圆心
CGPoint centerP = CGPointMake(ctxSize.width/2, ctxSize.height/2);
CGFloat radius = MIN(image.size.width, image.size.height)/2;
5.裁减圆形和绘制圆环。
/ 建立一个圆环/
UIBezierPath *pathLine = [UIBezierPath bezierPathWithArcCenter:centerP radius:radius startAngle:0 endAngle:2*M_PI clockwise:YES];
CGContextSetLineWidth(ctx, 10);
[[UIColor redColor]set];
CGContextAddPath(ctx, pathLine.CGPath);
CGContextDrawPath(ctx, kCGPathStroke);
/建立一个圆环
/裁减圆形
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:centerP radius:radius startAngle:0 endAngle:2*M_PI clockwise:YES];
CGContextAddPath(ctx, path.CGPath);
CGContextClip(ctx);
/裁减圆形 /
(注意:圆环在前,圆形在后,不然看不到圆环)
6.绘制图片
[image drawAtPoint:CGPointMake(margin, margin)];
7.获取裁剪后图片
UIImage *getImage = UIGraphicsGetImageFromCurrentImageContext();
//此时判断是否须要对图片进行适应屏幕的裁减。(好比长宽不等图片可能会出现压缩,须要裁剪成方形)
//7.截取图片(以前须要先将图片添加到图形上下文中,而后获取到再截取)
CGFloat x;
CGFloat y;
CGFloat w;
CGFloat h;
//a.当是竖屏照片时
if (getImage.size.height >=getImage.size.width) {
x = 0;
y = (getImage.size.height - 2*radius)/2;
}else{
//b.当时横屏照片时
y = 0;
x = (getImage.size.width - 2*radius)/2;
}
w = 2*radius;
h = w;
//为保证图片的正确显示,乘以屏幕缩放比
CGFloat scale = [UIScreen mainScreen].scale;
x *= scale;
y *= scale;
w *= scale;
h *= scale;
//截取 CG开头C语言。不用*
CGImageRef imageRef = CGImageCreateWithImageInRect(getImage.CGImage, CGRectMake(x, y, w, h));
//转换格式
getImage = [UIImage imageWithCGImage:imageRef];
8.关闭以前开启的上下文
UIGraphicsEndImageContext();
9.给imageView的image赋值。