【问题标题】:Manipulate pixels of NSImage in Cocoa在 Cocoa 中操作 NSImage 的像素
【发布时间】:2012-07-08 13:16:24
【问题描述】:

我想根据一些变量来修改 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 更改为上下文来绘制新图像。

谢谢!

【问题讨论】:

    标签: cocoa bitmapdata nsimage nsimageview


    【解决方案1】:

    this pageApple 上说:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多