CGImageCreatetesting模式不起作用(iOS)

我正在尝试为iOS 5.1设备创buildUIImagetesting模式。 目标UIImageView是320×240的大小,但我正在尝试创build一个160×120 UIImagetesting模式(未来,非testing模式图像将是这个大小)。 我想要盒子的上半部分是蓝色的,下半部分是红色的,但是看起来像是未初始化的内存会损坏图像的底部。 代码如下:

int width = 160; int height = 120; unsigned int testData[width * height]; for(int k = 0; k < (width * height) / 2; k++) testData[k] = 0xFF0000FF; // BGRA (Blue) for(int k = (width * height) / 2; k < width * height; k++) testData[k] = 0x0000FFFF; // BGRA (Red) int bitsPerComponent = 8; int bitsPerPixel = 32; int bytesPerRow = 4 * width; CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, &testData, (width * height * 4), NULL); CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); CGBitmapInfo bitmapInfo = kCGImageAlphaNoneSkipFirst; CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault; CGImageRef imageRef = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO,renderingIntent); UIImage *myTestImage = [UIImage imageWithCGImage:imageRef]; 

这应该看起来像堆栈溢出的另一个例子。 无论如何,我发现,当我减lesstesting模式的大小,图像的“腐败”部分增加。 另外奇怪的是,我在“腐败”的部分看到了红线,所以看起来我只是搞乱了组件的大小。 我错过了什么? 这感觉就像提供商的东西,但我没有看到它。

谢谢!

增加了截图。 以下是kCGImageAlphaNoneSkipFirst集的样子:

AlphaSkipFirst

这里是kCGImageAlphaFirst的样子:

在这里输入图像说明

你的像素数据是在一个自动variables,所以它存储在堆栈上:

 unsigned int testData[width * height]; 

您必须从声明此数据的函数返回。 这使得函数的堆栈框架被popup,并被其他函数重用,从而覆盖数据。

但是,您的图像仍然指向堆栈中相同地址的像素数据。 ( CGDataProviderCreateWithData不复制数据,它只是指它。)

修复:使用mallocCFMutableDataNSMutableData为堆上的像素数据分配空间。

您的图像包含alpha,然后通过跳过最重要的位(即图像的“B”部分)来告诉系统忽略。 尝试将其设置为kCGImageAlphaPremultipliedLast。

编辑:

现在我记得endianness,我意识到该程序可能是读取你的价值观,所以你可能真正想要的是kCGImageAlphaPremultipliedFirst