Objective c 目标C:将浮点数组显示为图像
在Cocoa应用程序中,我想在NSImageView中显示一个二维浮点数数组。为了使代码尽可能简单,首先将数据从float转换为NSData:Objective c 目标C:将浮点数组显示为图像,objective-c,nsdata,nsimageview,Objective C,Nsdata,Nsimageview,在Cocoa应用程序中,我想在NSImageView中显示一个二维浮点数数组。为了使代码尽可能简单,首先将数据从float转换为NSData: // 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
// 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)];
}
这是正确的方法吗?首先需要CGContext吗?我希望通过NSData来实现这一点
我注意到了早期的堆栈帖子:,,但是没有太多的运气得到这些工作的变化。谢谢您的建议。您可以使用
NSBitmapImageRep
逐浮点构建NSImage
浮点
有趣的是,它的一个初始值设定项拥有所有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)
至少有很好的记录。一旦您通过在平面中提供浮点数组构建了它
,您就可以获得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
。Ok使其正常工作。我以前尝试过NSBitmapImageRep(谢谢Tim),但我缺少的部分是将浮点数据正确转换为字节数组。NSData不这样做,返回nil。因此,解决方案并不需要一个接一个地建立NSImage浮点。事实上,人们可以类似地构建bitmapContext(使用CGBitmapContextCreate(上面HotLicks提到过)),一旦浮点数数据被正确表示,这也会起作用。我想你可能需要使用CGContext。谢谢Tim,正如你在最后提出的,我认为问题可能是“nsdata”上面定义的位图格式不正确;如何将浮点转换为“正确的”位图格式?请详细说明您的答案,以解释“将浮点数据正确转换为字节数组”。显示执行该转换的代码将非常好。
+ (id)imageRepWithData:(NSData *)bitmapData