如何在不使用屏幕比例的情况下将 UIView/UIImageView 渲染为具有图像精确大小的 UIImage?

How to render UIView/UIImageView to UIImage with exact size of the image without using the scale of screen?

我进行了很多搜索,并尝试了我在 Whosebug 中可以找到的每一种方法,其中 none 行之有效。假设我有一个 UIView,它有一个 UIImageView,其中包含一个大小为 1800x2300 的 UIImage,这显然大于 iPhone 7/8 屏幕的大小,因此即使使用屏幕比例也无助于呈现此视图包含这个 Image.And 是的,我也尝试过 ,我想要一个比我的视网膜屏幕尺寸更大的渲染,但它不适合我。这些是我尝试过的方法,它们不会渲染任何大于我的 imageRect * Scale of my screen 的尺寸

    // Approach 1
    @autoreleasepool{
        //imageRect is a CGRect which is the rect I defined for my 
        //UIImageView to be aspect fitted in it.
        //_viewWithLoadedImages is the UIView containing two transparent 
        //UIImageViews on top of each other, each containing images 
        //bigger than screen size of iPhones.

        UIGraphicsBeginImageContextWithOptions(imageRect.size,NO,0);
        CGContextRef c = UIGraphicsGetCurrentContext();
        CGContextConcatCTM(c, CGAffineTransformMakeTranslation(-imageRect.origin.x, -imageRect.origin.y));
        [_viewWithLoadedImages.layer renderInContext:c];
        UIImage*renderedImage = 
        UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return renderedImage;
    }

    //Approach 2
    @autoreleasepool{
        UIGraphicsImageRenderer * Renderer = [[UIGraphicsImageRenderer alloc] initWithBounds:imageRect];
        self.tempImage=[Renderer imageWithActions:^(UIGraphicsImageRendererContext*_Nonnull context){[_viewWithLoadedImages.layer renderInContext:context.CGContext];}];
            return self.tempImage;
    }

    //Approach 3 
    UIGraphicsBeginImageContextWithOptions(imagerect, NO, 0.0f);
    [_viewWithLoadedImages drawViewHierarchyInRect:imagerect afterScreenUpdates:YES];
    UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshotImage;

它们的输出大小都等于 ImageRect * ScreenScale 的大小,但我想从我的 UIView (_viewWithLoadedImages) 输出更大的图像,我该怎么办?我几乎尝试了一切。 非常感谢任何帮助。

假设您有两个 UIImageView,并且可以使用其中之一来调整最终图像的大小,您可以这样做。

// Desired dimension in pixels
CGRect frame = CGRectMake(0.0, 0.0,
                          _imageView1.image.size.width * _imageView1.image.scale,
                         _imageView1.image.size.height * _imageView1.image.scale);

// Use scale 1.0 for pixel size
UIGraphicsBeginImageContextWithOptions(frame.size, NO, 1.0);

// Draw the images on top of each other
[_imageView1.image drawInRect:frame];
[_imageView2.image drawInRect:frame];

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return image;