1 //1.加载要裁剪的图片 2 UIImage * image = [UIImage imageNamed:@"me"]; 3 4 //2.开启一个比图片稍大的图形上下文 (bitmap) 5 6 CGFloat margin = 5; 7 8 //2.1计算图形上下文的size 9 CGSize ctxSize = CGSizeMake(image.size.width + 2 * margin, image.size.height + 2 * margin); 10 11 UIGraphicsBeginImageContextWithOptions(ctxSize, NO, 0.0); 12 13 //3.获取刚刚开启的图形上下文对象 14 CGContextRef ctx = UIGraphicsGetCurrentContext(); 15 16 17 //-------------------画一个圆环-------------------- 18 //4.创建一个圆环路径 19 //设置圆心 20 CGPoint centerP = CGPointMake(ctxSize.width/2, ctxSize.height/2); 21 22 //设置半径 23 CGFloat radius = MIN(image.size.width, image.size.height)/2; 24 25 UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:centerP radius:radius startAngle:0 endAngle:2*M_PI clockwise:YES]; 26 //设置圆环的颜色和线宽 27 CGContextSetLineWidth(ctx, 5); 28 29 [[UIColor redColor] set]; 30 31 CGContextAddPath(ctx, path.CGPath); 32 33 // //6.执行裁剪 34 // CGContextClip(ctx); 35 36 //4.1 渲染 37 CGContextStrokePath(ctx); 38 //-------------------画一个圆环-------------------- 39 40 41 42 //-------------------画一个裁剪区域-------------------- 43 //5.创建裁剪的路径 44 UIBezierPath * path1 = [UIBezierPath bezierPathWithArcCenter:centerP radius:radius startAngle:0 endAngle:2*M_PI clockwise:YES]; 45 46 //5.1 把路径添加到图形上下文中 47 CGContextAddPath(ctx, path1.CGPath); 48 49 //6.执行裁剪 50 CGContextClip(ctx); 51 52 53 //-------------------画一个裁剪区域-------------------- 54 55 56 57 58 59 60 //7.绘制图片 61 [image drawAtPoint:CGPointMake(margin, margin)]; 62 63 //8.获取图片 64 UIImage * getImage = UIGraphicsGetImageFromCurrentImageContext(); 65 66 //8.1 结束图形上下文 67 UIGraphicsEndImageContext(); 68 69 //9.保存 70 self.imageView.image = getImage; 71 72 UIImageWriteToSavedPhotosAlbum(getImage, nil, nil, nil); 73 74 //9.1 保存沙盒 75 76 NSString * documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 77 78 NSString * fileName = [documents stringByAppendingPathComponent:@"002.png"]; 79 80 NSData * imageData = UIImagePNGRepresentation(getImage); 81 82 [imageData writeToFile:fileName atomically:YES];
浙公网安备 33010602011771号