2012-02-02 53 views
4

在可可應用程序中,我希望在NSImageView中顯示浮動的二維數組。爲了使代碼儘可能的簡單,通過從浮點數轉換的數據NSData的開始:Objective-C:將浮動數組顯示爲圖像

// dataArray: an Nx by Ny array of floats 
NSMutableData *nsdata = [NSMutableData dataWithCapacity:0]; 
long numPixels = Nx*Ny; 
for (int i = 0; i < numPixels; i++) { 
    [nsdata appendBytes:&dataArray[i] length:sizeof(float)]; 
} 

現在嘗試顯示數據(顯示爲空白):

[theNSImageView setImage:[[NSImage alloc] initWithData:nsdata]]; 

是這是正確的方法?首先需要一個CGContext?我希望用NSData來完成這個任務。

已經注意到前面的堆棧的帖子:32 bit dataclose but in reversealmost worked but no NSDatacolor image data here,但沒有多少運氣得到這些工作的變化。感謝您的任何建議。

+0

我想你可能需要在CGContext牀上。 – 2012-02-02 19:53:48

回答

0

好吧,它的工作。我之前嘗試過NSBitmapImageRep(感謝Tim),但我缺少的部分是正確地將我的浮點數據轉換爲字節數組。 NSData不會這樣做,並返回nil。所以這個解決方案並不需要建立一個NSImage浮點浮點數。實際上,可以類似地構建一個bitmapContext(使用CGBitmapContextCreate(由上面的HotLicks提到)),並且一旦正確表示浮點數據就可以工作。

+0

您能否詳細說明您的答案,以解釋「正確地將我的浮點數據轉換爲字節數組」。顯示執行該轉換的代碼會很好。 – rene 2017-12-14 06:08:46

2

您可以使用NSBitmapImageRep構建NSImage float-by-float。

有趣的是,它的initialisers的一個在所有的Cocoa中最長的方法名:

- (id)initWithBitmapDataPlanes:(unsigned char **)planes 
        pixelsWide:(NSInteger)width 
        pixelsHigh:(NSInteger)height 
       bitsPerSample:(NSInteger)bps 
       samplesPerPixel:(NSInteger)spp 
         hasAlpha:(BOOL)alpha 
         isPlanar:(BOOL)isPlanar 
       colorSpaceName:(NSString *)colorSpaceName 
        bitmapFormat:(NSBitmapFormat)bitmapFormat 
        bytesPerRow:(NSInteger)rowBytes 
        bitsPerPixel:(NSInteger) 

它至少有據可查。一旦你把它建立在planes提供浮標陣就可以再拿到NSImage把你的觀點:

NSImage *image = [[NSImage alloc] initWithCGImage:[bitmapImageRep CGImage] size:NSMakeSize(width,height)]; 

或者稍微乾淨

NSImage *image = [[[NSImage alloc] init] autorelease]; 
[im addRepresentation:bitmapImageRep]; 

有它只是使用的初始化器一個NSData容器:

+ (id)imageRepWithData:(NSData *)bitmapData 

雖然這取決於你的bitmapData包含正確的位圖之一墊。

+0

感謝蒂姆,正如你在最後建議的那樣,我認爲問題可能是上面定義的「nsdata」不是正確的位圖格式之一;我如何進行從浮點到「適當」位圖格式的轉換? – 2012-02-03 04:40:32