1 #import "ViewController.h" 2 3 @interface ViewController () 4 @property (weak, nonatomic) IBOutlet UIImageView *imageView; 5 6 @end 7 8 @implementation ViewController 9 //点击裁剪 按钮事件 10 - (IBAction)clipBtnClick:(id)sender 11 { 12 //1.加载要裁剪的图片 13 UIImage * image = [UIImage imageNamed:@"dst2"]; 14 15 //2.开启一个图形上下文 (bitmap 大小和要裁剪的图片大小一样) 16 UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0); 17 18 //3.获取图形上下文 19 CGContextRef ctx = UIGraphicsGetCurrentContext(); 20 21 //4.创建路径 22 //设置圆心 23 CGPoint centerP = CGPointMake(image.size.width/2, image.size.height/2); 24 //设置半径 25 CGFloat radius = MIN(image.size.width, image.size.height)/2; 26 27 UIBezierPath * path = [UIBezierPath bezierPathWithArcCenter:centerP radius:radius startAngle:0 endAngle:2 * M_PI clockwise:YES]; 28 29 //5.把路径添加到图形上下文中 30 CGContextAddPath(ctx, path.CGPath); 31 32 //6.执行裁剪 33 CGContextClip(ctx); 34 35 36 //7.绘制图片 37 [image drawAtPoint:CGPointZero]; 38 39 //8.获取图片 40 UIImage * getImage = UIGraphicsGetImageFromCurrentImageContext(); 41 42 //8.1 结束图形上下文 43 UIGraphicsEndImageContext(); 44 45 //8.2 裁剪图片 46 //其中x,y需要根据实际情况计算 47 CGFloat x = 0; 48 CGFloat y = (image.size.height - 2 * radius)/2; 49 50 CGFloat w = 2 * radius; 51 CGFloat h = w; 52 53 //获取屏幕的缩放比 54 CGFloat scale = [UIScreen mainScreen].scale; 55 x *= scale; 56 y *= scale; 57 58 w *= scale; 59 h *= scale; 60 61 CGImageRef imageRef = CGImageCreateWithImageInRect(getImage.CGImage, CGRectMake(x, y, w, h)); 62 63 //获取裁剪后的图片 64 getImage = [UIImage imageWithCGImage:imageRef]; 65 66 self.imageView.image = getImage; 67 68 //9.保存 69 70 //9.1 保存相册 71 UIImageWriteToSavedPhotosAlbum(getImage, self, @selector(image:didFinishSavingWithError:contextInfo:), @"hello word"); 72 //9.2 保存沙盒 73 74 NSString * documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 75 76 //拼接文件名 77 NSString * fileName = [documents stringByAppendingPathComponent:@"001.png"]; 78 79 //把UIimage--->NSData 80 NSData * imageData = UIImagePNGRepresentation(getImage); 81 82 [imageData writeToFile:fileName atomically:YES]; 83 84 NSLog(@"%@",fileName); 85 } 86 //保存相册方法 87 - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo 88 { 89 NSLog(@"保存完毕 %@",contextInfo); 90 } 91 92 - (void)savePhoto 93 { 94 NSLog(@"保存完毕"); 95 } 96 - (void)viewDidLoad { 97 [super viewDidLoad]; 98 // Do any additional setup after loading the view, typically from a nib. 99 } 100 101 - (void)didReceiveMemoryWarning { 102 [super didReceiveMemoryWarning]; 103 // Dispose of any resources that can be recreated. 104 } 105 106 @end
浙公网安备 33010602011771号