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

时间:2018-01-18 12:02:05

标签: objective-c uiview uiimageview uiimage uigraphicscontext

我已经搜索了很多,并尝试了我在StackOverflow中找到的每一种方法,但没有一种方法有效。假设我有一个UIView,其UIImageView包含一个大小为1800x2300的UIImage,这显然比iPhone 7/8的屏幕大,所以即使使用Screen scale也无法渲染包含此Image的View。是的,我也试过https://stackoverflow.com/questions/4334233/how-to-capture-uiview-to-uiimage-without-loss-of-quality-on-retina-display,我想要一个比我的视网膜屏幕尺寸更大的渲染,它不适合我。这些是我尝试这样做的方式,它们不会渲染任何大于我的imageRect *屏幕比例的大小

    // 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)我该怎么办?我几乎尝试了一切。 非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

假设您有两个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;