iOS:使用自定义分辨率保存图像

Mc.*_*ver 15 iphone xcode objective-c ipad ios

嗨我尝试捕获视图然后将图像另存为照片库,但我需要为捕获的图像创建自定义分辨率,这是我的代码但是当应用程序保存图像时分辨率很低!

UIGraphicsBeginImageContextWithOptions(self.captureView.bounds.size, self.captureView.opaque, 0.0);

[self.captureView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * screenshot = UIGraphicsGetImageFromCurrentImageContext();

CGRect cropRect = CGRectMake(0 ,0 ,1435 ,1435);
CGImageRef imageRef = CGImageCreateWithImageInRect([screenshot CGImage], cropRect);
CGImageRelease(imageRef);

UIImageWriteToSavedPhotosAlbum(screenshot , nil, nil, nil);

UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)

但iPhone的分辨率为:320 x 320,视网膜为:640 x 640

如果你能帮助我解决这个问题,我将不胜感激.

idz*_*idz 16

你的代码非常接近.您需要做的是以自定义分辨率重新渲染屏幕截图.我修改了你的代码来做到这一点:

UIView* captureView = self.view;

/* Capture the screen shoot at native resolution */
UIGraphicsBeginImageContextWithOptions(captureView.bounds.size, captureView.opaque, 0.0);
[captureView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * screenshot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

/* Render the screen shot at custom resolution */
CGRect cropRect = CGRectMake(0 ,0 ,1435 ,1435);
UIGraphicsBeginImageContextWithOptions(cropRect.size, captureView.opaque, 1.0f);
[screenshot drawInRect:cropRect];
UIImage * customScreenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

/* Save to the photo album */
UIImageWriteToSavedPhotosAlbum(customScreenShot , nil, nil, nil);
Run Code Online (Sandbox Code Playgroud)

请注意,如果捕获视图不是方形,则图像将会失真.保存的图像将始终为正方形和1435x1435像素.


小智 7

看看这个答案.代码包括旋转但是提问者问了同样的问题:"如何从UIImageView以全分辨率获取图像?"

复制的内容(如果删除或其他):

- (UIImage *)capturedView
{
    float imageScale = sqrtf(powf(self.captureView.transform.a, 2.f) + powf(self.captureView.transform.c, 2.f));    
    CGFloat widthScale = self.captureView.bounds.size.width / self.captureView.image.size.width;
    CGFloat heightScale = self.captureView.bounds.size.height / self.captureView.image.size.height;
    float contentScale = MIN(widthScale, heightScale);
    float effectiveScale = imageScale * contentScale;

    CGSize captureSize = CGSizeMake(enclosingView.bounds.size.width / effectiveScale, enclosingView.bounds.size.height / effectiveScale);

    NSLog(@"effectiveScale = %0.2f, captureSize = %@", effectiveScale, NSStringFromCGSize(captureSize));

    UIGraphicsBeginImageContextWithOptions(captureSize, YES, 0.0);        
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextScaleCTM(context, 1/effectiveScale, 1/effectiveScale);
    [enclosingView.layer renderInContext:context];   
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return img;
}
Run Code Online (Sandbox Code Playgroud)