我正在使用AVFoundation
在相机应用程序中实现缩放功能。我正在缩放我的预览视图,如下所示:
[videoPreviewView setTransform:CGAffineTransformMakeScale(cameraZoom, cameraZoom)];
现在,在我拍照后,我想在将图片保存到相机胶卷之前,先用cameraZoom
值缩放/裁剪图片。我应该如何最好地做到这一点?
编辑:使用贾斯汀的答案:
CGRect imageRect = CGRectMake(0.0f, 0.0f, image.size.width, image.size.height);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], imageRect);
CGContextRef bitmapContext = CGBitmapContextCreate(NULL, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), CGImageGetColorSpace(imageRef), CGImageGetBitmapInfo(imageRef));
CGContextScaleCTM(bitmapContext, scale, scale);
CGContextDrawImage(bitmapContext, imageRect, imageRef);
CGImageRef zoomedCGImage = CGBitmapContextCreateImage(bitmapContext);
UIImage* zoomedImage = [[UIImage alloc] initWithCGImage:imageRef];
它正在缩放图像,但它并没有占据图像的中心,而是似乎占据了右上角区域。(我不太肯定)。
另一个问题(我本应该在OP中更清楚)是,图像保持不变的分辨率,但我宁愿把它裁剪下来。
+ (UIImage*)croppedImageWithImage:(UIImage *)image zoom:(CGFloat)zoom
{
CGFloat zoomReciprocal = 1.0f / zoom;
CGPoint offset = CGPointMake(image.size.width * ((1.0f - zoomReciprocal) / 2.0f), image.size.height * ((1.0f - zoomReciprocal) / 2.0f));
CGRect croppedRect = CGRectMake(offset.x, offset.y, image.size.width * zoomReciprocal, image.size.height * zoomReciprocal);
CGImageRef croppedImageRef = CGImageCreateWithImageInRect([image CGImage], croppedRect);
UIImage* croppedImage = [[UIImage alloc] initWithCGImage:croppedImageRef scale:[image scale] orientation:[image imageOrientation]];
CGImageRelease(croppedImageRef);
return croppedImage;
}
缩放:
- 创建
CGBitmapContext
- 更改上下文的转换(
CGContextScaleCTM
) - 绘制图像(
CGContextDrawImage
)-您传递的矩形可用于偏移原点和/或尺寸 - 根据上下文生成新的CGImage(
CGBitmapContextCreateImage
)
至作物:
- 创建CCD_ 7。传递NULL,以便上下文为位图创建缓冲区
- 按原样绘制图像(
CGContextDrawImage
) - 使用缓冲区的第一个上下文像素数据的偏移量为裁剪创建
CGBitmapContext
(具有新维度) - 从第二上下文生成新的CGImage(
CGBitmapContextCreateImage
)