最近有个需求需要在拍照时截取线框的部分存储在相册,就写了个demo。
这是相框的位置设定
CGFloat height = self.bounds.size.height;
CGFloat width = self.bounds.size.width;
UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake((width - width * 3 / 4) / 2, height * 0.3, width * 3 / 4 , width * 3 / 12)];
imageV.clipsToBounds = YES;
imageV.layer.borderColor = [UIColor whiteColor].CGColor;
imageV.layer.borderWidth = 0.5;
[self addSubview:imageV];
按说截取的frame要和这个frame一致,但是后面把image放到屏幕为了清晰度用的是 UIGraphicsBeginImageContextWithOptions(size,YES,[UIScreen mainScreen].scale); 而不是 UIGraphicsBeginImageContext(size); 所以截取位置的frame _imageRect就要用相应的
CGFloat height2 = height * [UIScreen mainScreen].scale;CGFloat width2 = width * [UIScreen mainScreen].scale;_imageRect = CGRectMake((width2 - width2 * 3 / 4) / 2, height2 * 0.3, width2 * 3 / 4 , width2 * 3 / 12);
这是image放到屏幕的函数
+(UIImage*)image:(UIImage *)image scaleToSize:(CGSize)size{
// 得到图片上下文,指定绘制范围// UIGraphicsBeginImageContext(size);
UIGraphicsBeginImageContextWithOptions(size,YES,[UIScreen mainScreen].scale);
// 将图片按照指定大小绘制
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
// 从当前图片上下文中导出图片
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 当前图片上下文出栈
UIGraphicsEndImageContext();
// 返回新的改变大小后的图片
return scaledImage;}
截取image的函数
+(UIImage *)imageFromImage:(UIImage *)image inRect:(CGRect)rect{
//将UIImage转换成CGImageRef
CGImageRef sourceImageRef = [image CGImage];
//按照给定的矩形区域进行剪裁
CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);
//将CGImageRef转换成UIImage
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
//返回剪裁后的图片
return newImage;}
这是自己的拙见,欢迎指正,🙏。