【问题标题】:How to 'Flatten' multiple UIImageViews into ONE?如何将多个 UIImageViews 扁平化为一个?
【发布时间】:2010-11-18 05:04:36
【问题描述】:

我觉得这不是一件容易的事,但我需要将 UIImageView 与位于其上方的另一个 UIImage 视图组合或展平。例如:我有两个 UIImageViews。其中一个有一个草地的 UIImage(1200 x 1200 像素)。另一个是篮球的 UIImage(128 x 128 像素),它位于草地图像上方,使篮球看起来在草地上。我希望能够将叠加的 UIImageViews 作为单个图像文件保存到我的相册中,这意味着我需要以某种方式组合这两个图像。这将如何实现? (注意:截屏(320 x 480 像素)不是可接受的解决方案,因为我希望保留 1200 x 1600 像素的大小。

问题:
如何将多个 UIImageView 拼合为一个并保存生成的图像,同时保留大小/分辨率。

【问题讨论】:

    标签: iphone uiimage core-graphics pixel flatten


    【解决方案1】:

    为什么不将原始 UIImages 叠加到背景缓冲区中,然后将组合图像写入文件?下面是一个如何将两个图像绘制到同一个缓冲区的示例:

    CGImageRef bgimage = [bguiimage CGImage];
    width = CGImageGetWidth(bgimage);
    height = CGImageGetHeight(bgimage);
    
    // Create a temporary texture data buffer
    GLUbyte* data = (GLubyte *) malloc(width * height * 4);
    assert(data);
    
    // Draw image to buffer
    CGContextRef ctx = CGBitmapContextCreate(data, width, height, 8, width * 4, CGImageGetColorSpace(image), kCGImageAlphaPremultipliedLast);
    assert(ctx);
    
    // Flip image upside-down because OpenGL coordinates differ
    CGContextTranslateCTM(ctx, 0, height);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    
    CGContextDrawImage(ctx, CGRectMake(0, 0, (CGFloat)width, (CGFloat)height), bgimage);
    
    CGImageRef ballimage = [balluiimage CGImage];
    bwidth = CGImageGetWidth(ballimage);
    bheight = CGImageGetHeight(ballimage);
    
    float x = (width - bwidth) / 2.0;
    float y = (height - bheight) / 2.0;
    CGContextDrawImage(ctx, CGRectMake(x, y, (CGFloat)bwidth, (CGFloat)bheight), ballimage);
    
    CGContextRelease(ctx);
    

    【讨论】:

    • 感谢您的建议。这会保留原始图像的分辨率/像素,还是它们最终具有与保存它们的视图相同的大小?
    • 它会保留分辨率,因为您绘制的是原始图像。
    【解决方案2】:

    这会获取任何视图并从中生成 UIImage。任何视图及其子视图都将被“展平”为 UIImage,您可以将其显示或保存到磁盘。

      - (UIImage*)imageFromView{
    
        UIImage *image;
    
        UIGraphicsBeginImageContext(self.view.bounds.size);
        [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return image;
    
    }
    

    【讨论】:

    • 顺便说一句,Corey,有没有办法做到这一点(你上面的代码),同时保留作为基础层的视图的图像分辨率(你的代码中的 self.view.layer)?我有一张大小为 1200 x 1600 的照片,但在处理后(使用您的代码),生成的图像具有作为其容器的 UIImageView 的像素大小(320 x 427)。
    • 我不能肯定地说,但龙舌兰酒使用的策略似乎可以做到这一点。我使用的方法只会以屏幕分辨率捕获屏幕上的内容。它又快又脏,但有效。如果您需要更好的结果,则需要按照他的说明将图像绘制到缓冲区中。当然,由于这是 iPhone,如果有一种方法可以让您在不影响用户体验的情况下减小图像大小,那么出于内存/性能原因,您可能需要考虑它。
    • 要保持图像分辨率只需使用UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0.0)
    猜你喜欢
    • 2019-04-23
    • 1970-01-01
    • 2020-06-29
    • 2022-10-05
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    相关资源
    最近更新 更多