我正在我的代码中从头开始创建一个 NSImage
。首先,我分配一个字节数组:
pixels = malloc( (int)( size.width * size.height) * 4 * 8 * sizeof(unsigned char));
然后我尝试创建一个测试图像,它应该包含从左侧的纯黑色到右侧的纯红色的渐变:
-(void)generateTestImage{
int idx =0;
for( int i=0; i<(int)(size.height); i++){// Rows
for (int j=0; j<(int) size.width; j++){// Columns
pixels[ idx + 0 ] = 255 * ((float) j / size.width); // r
pixels[ idx + 1 ] = 0; // g
pixels[ idx + 2 ] = 0; // b
pixels[ idx + 3 ] = 255;// a
idx += 4;
}
}
}
最后,我使用以下方法将字节数组转换为 NSImage
:
-(void) convertPixelsToImage{
if (renderImage == NULL)
renderImage = [[NSImage alloc] initWithSize:size];
else{
NSArray *prevReps = [renderImage representations];
for (id r in prevReps)
[renderImage removeRepresentation:r];
}
NSLog(@"Creating bitmapImageReprsentation with size:%@", NSStringFromSize(size));
NSBitmapImageRep *imgRep =
[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:&pixels
pixelsWide:size.width
pixelsHigh:size.height
bitsPerSample:8
samplesPerPixel:sampPerPix
hasAlpha:true
isPlanar:false
colorSpaceName:NSDeviceRGBColorSpace
bitmapFormat:0
bytesPerRow:0
bitsPerPixel:0];
[renderImage addRepresentation:imgRep];
}
但是,生成的图像不是我所期望的。
这是索引偏移的放大 View
似乎我的索引已关闭,因为渐变模式在每行上向左移动了 9 个像素。
此外,我对图像底部的白色条纹感到困惑...
在过去的几个小时里,我尝试了各种索引方案,但没有一个能解决问题。我已验证我在整个代码中使用了相同的 size
。此外,我已经验证生成的图像具有正确的尺寸,但它的内容是关闭的。
这段代码有明显的问题吗?关于如何解决此问题的任何想法?
最佳答案
请记住,行四舍五入到某个边界——我想是 16 像素。
关于objective-c - 从字节数组创建 NSImage 的令人费解的索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13212955/