缩放UIImage/CGImage

2 core-graphics image-processing uiimage cgimage ios

我正在使用相机应用程序实现缩放功能AVFoundation.我正在缩放我的预览视图,如下所示:

[videoPreviewView setTransform:CGAffineTransformMakeScale(cameraZoom, cameraZoom)];
Run Code Online (Sandbox Code Playgroud)

现在,在拍完照片之后,我想在将照片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];
Run Code Online (Sandbox Code Playgroud)

它正在缩放图像,但它没有占据它的中心,而是似乎占据了右上角区域.(我不是积极的).

另一个问题(我应该在OP中更清楚)是图像保持相同的分辨率,但我宁愿将其裁剪掉.

小智 6

+ (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;
}
Run Code Online (Sandbox Code Playgroud)