ios - CGImageCreate 测试模式不工作 (iOS)

标签 ios ios5 uiimage cgimageref

我正在尝试为 iOS 5.1 设备创建一个 UIImage 测试模式。目标 UIImageView 的大小为 320x240,但我试图创建一个 160x120 的 UIImage 测试模式( future ,非测试模式图像将是这个大小)。我希望盒子的上半部分为蓝色,下半部分为红色,但我得到的图像底部看起来像是未初始化的内存。代码如下:

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];

这应该看起来像 Stack Overflow 上的另一个例子。无论如何,我发现当我减小测试图案的尺寸时,图像的“损坏”部分会增加。同样奇怪的是,我在“损坏”部分看到了红色线条,所以看起来我并没有弄乱组件的大小。我错过了什么?感觉像是提供程序中的东西,但我没有看到它。

谢谢!

添加了屏幕截图。这是 kCGImageAlphaNoneSkipFirst 集的样子:

AlphaSkipFirst

这是 kCGImageAlphaFirst 的样子:

enter image description here

最佳答案

您的像素数据在一个自动变量中,因此它存储在堆栈中:

unsigned int testData[width * height];

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

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

解决方法:使用 mallocCFMutableDataNSMutableData 为堆上的像素数据分配空间。

关于ios - CGImageCreate 测试模式不工作 (iOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9864548/

相关文章:

ios - 如何测试 UIWebView 对 JavaScript 的 10MB 限制?

ios - 在pfcloud函数中返回 bool 值

ios - 旋转时自动调整 AVCaptureVideoPreviewLayer 大小的问题

iphone - 自定义 UITableView 部分未在 iOS5 中加载

ios - 条纹线突然出现

ios - 如何通过 Interface Builder 将 UIImage 对象放置在 UITableViewController View 的底部

iOS - NSFileManager 文件不存在

ios - 从 NSTimer 回到主线程

Xcode 界面生成器。这些自动调整大小的蒙版设置有何不同?

ios - 在 uiimage 中以正确的方式快速显示小或大的高度、宽度图像