objective-c - 从字节数组创建 NSImage 的令人费解的索引错误

标签 objective-c c image indexing nsimage

我正在我的代码中从头开始创建一个 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];
}

但是,生成的图像不是我所期望的。

enter image description here

这是索引偏移的放大 View enter image description here

似乎我的索引已关闭,因为渐变模式在每行上向左移动了 9 个像素。

此外,我对图像底部的白色条纹感到困惑...

在过去的几个小时里,我尝试了各种索引方案,但没有一个能解决问题。我已验证我在整个代码中使用了相同的 size。此外,我已经验证生成的图像具有正确的尺寸,但它的内容是关闭的。

这段代码有明显的问题吗?关于如何解决此问题的任何想法?

最佳答案

请记住,行四舍五入到某个边界——我想是 16 像素。

关于objective-c - 从字节数组创建 NSImage 的令人费解的索引错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13212955/

相关文章:

iphone - 允许用户在 iCloud 不可用时编辑/查看现有文档

objective-c - presentModalViewController 未被释放

Java程序无法正确访问图像

css - 什么可能导致 Internet Explorer 6 中图像加载间歇性问题?

ios - 完成处理程序和返回值

objective-c - objective c avaudioplayer 不播放声音

c - 如何制作 Qt 线程包装器

c - 找不到段错误

c - 在 IPv6 中使用 resolv.h 的名称解析器

php - 无法使用 PHP 的 imagerotate 旋转图像