我正在使用 AVFoundation
在相机应用程序中实现缩放功能。我正在像这样缩放我的预览 View :
[videoPreviewView setTransform:CGAffineTransformMakeScale(cameraZoom, cameraZoom)];
现在,拍完照片后,我想在将照片保存到相机胶卷之前使用 cameraZoom
值缩放/裁剪照片。我应该如何最好地做到这一点?
编辑:使用 Justin 的回答:
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;
}
关于ios - 缩放 UIImage/CGImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8959293/