XCODE 5 iOS7 如何在不丢失透明背景的情况下将 UIImage (PNG) 转换为 NSData

fii*_*go0 5 objective-c uiimage uiimagepngrepresentation ios7

我有一种方法可以接收UIImage我将其转换为NSData并发出发布该数据的请求,它适用于 iOS 6,但是当我尝试使用 iOS 7 时,图像丢失了透明背景。

这是我迄今为止尝试过的:

-(void)post:(UIImage *)firm name:
{

    int x = 350;

    NSData *imageData = UIImagePNGRepresentation(firm);
    UIImage *image=[UIImage imageWithData:imageData];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, x, 40, 50)];
    imageView.backgroundColor = [UIColor clearColor];
    imageView.image = image;


    NSData *imageData2 = [NSData dataWithData:UIImagePNGRepresentation(firm)];
    UIImage *image2=[UIImage imageWithData:imageData2];
    UIImageView *imageView2 = [[UIImageView alloc]initWithFrame:CGRectMake(160, x, 40, 50)];
    imageView2.image = image2;

    UIImageView *imageView3 = [[UIImageView alloc]initWithFrame:CGRectMake(110, x, 40, 50)];
    imageView3.image = firm;

    UIImage * img = [UIImage imageWithData:UIImagePNGRepresentation(image)];
    UIImageView *imageView4 = [[UIImageView alloc]initWithFrame:CGRectMake(210, x, 40, 50)];
    imageView4.image = img;

    [self.view addSubview:imageView];
    [self.view addSubview:imageView2];
    [self.view addSubview:imageView3];
    [self.view addSubview:imageView4];
Run Code Online (Sandbox Code Playgroud)

imageView3我只是在没有背景的情况下显示它(直到这里我一切都很好)但是当我转换为NSData然后将其恢复为UIImage它时会失去透明度,

在 iOS 7 上运行的代码

在此处输入图片说明

在 iOS 6 及更低版本上运行的相同代码完美运行!!

在此处输入图片说明

我在Github 示例上创建了一个示例 os 我的问题

Rob*_*Rob 2

当我UIImagePNGRepresentation在 iOS7 上使用具有透明度的图像时,透明度会被保留。

例如,使用此图像:

中风

当我使用您的代码渲染它时,我得到:

在此输入图像描述

也许你一开始的图像有些问题。


该问题似乎源于创建图像的 OpenGLES 代码。正如这里所讨论的,您似乎需要使用

glClearColor(0.0, 0.0, 0.0, 0.0);
Run Code Online (Sandbox Code Playgroud)

代替

glClearColor(1.0, 1.0, 1.0, 0.0);
Run Code Online (Sandbox Code Playgroud)

我还使用了kCGImageAlphaPremultipliedLast的值CGBitmapInfo

完成所有这些,使调用变得CGImageCreateWithMaskingColors不必要,并且当您调用 时,生成的图像似乎正确保留了 Alpha 通道UIImagePNGRepresentation