1

我想根据一些变量修改 NSImage 像素的颜色,而不使用太多依赖于工具包的库(例如:CIImage)。这样以后我就可以专注于像素操作算法并保持它们独立于平台。

我的方法是继承 NSImage 并添加一个属性

NSBitmapImageRep *originalImage;

在启动期间,我会:

-(id) initWithContentsOfFile:(NSString *)fileName
{
    if([super initWithContentsOfFile:fileName]){
        NSRect rect = NSMakeRect(0.0, 0.0, self.size.width, self.size.height);
        [self lockFocus];
        originalImage = [[NSBitmapImageRep alloc] initWithFocusedViewRect:rect];
        [self unlockFocus];
    }
    return self;
}

现在,当我尝试更新图像时,我会这样做:

-(void) updateWithVariables:...
{
    NSInteger width = [originalImage pixelsWide];
    NSInteger height = [originalImage pixelsHigh];
    NSInteger count = width * height * 4;

    unsigned char *bytes = (unsigned char *)calloc(count, sizeof(unsigned char));

    // bytes manipulation

    NSBitmapImageRep* newImg = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:&bytes
                                                                       pixelsWide:width
                                                                       pixelsHigh:height
                                                                    bitsPerSample:[originalImage bitsPerSample]
                                                                  samplesPerPixel:[originalImage samplesPerPixel]
                                                                         hasAlpha:TRUE
                                                                         isPlanar:[originalImage isPlanar]
                                                                   colorSpaceName:[originalImage colorSpaceName]
                                                                     bitmapFormat:[originalImage bitmapFormat]
                                                                      bytesPerRow:[originalImage bytesPerRow]
                                                                     bitsPerPixel:[originalImage bitsPerPixel]];
    while([[self representations] count] > 0){
        NSBitmapImageRep *rep = [[self representations] objectAtIndex: 0];
        [self removeRepresentation:rep];
    }

    [self addRepresentation:newImg];
    [newImg release];
}

但是图像没有改变。我不确定是否必须使用表示或将包含的 NSImageView 更改为上下文来绘制新图像。

谢谢!

4

1 回答 1

0

此页面上,Apple 说:

将 NSImage 及其图像表示视为不可变对象。NSImage 的目标是提供一种在目标画布上显示图像的有效方式。避免直接操作图像表示的数据,特别是如果有其他操作数据的替代方法,例如将图像和其他一些内容合成到新的图像对象中。

因此,当您希望像素发生变化时,您可能应该创建一个新图像。

于 2012-07-08T15:27:11.743 回答