加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Objective-C:将浮点数组显示为图像

发布时间:2020-12-16 07:28:50 所属栏目:百科 来源:网络整理
导读:在 Cocoa应用程序中,我想在NS ImageView中显示一个2d浮点数组.为了使代码尽可能简单,首先将数据从float转换为NSData: // dataArray: an Nx by Ny array of floatsNSMutableData *nsdata = [NSMutableData dataWithCapacity:0];long numPixels = Nx*Ny;for (
在 Cocoa应用程序中,我想在NS ImageView中显示一个2d浮点数组.为了使代码尽可能简单,首先将数据从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 appendBytes:&dataArray[i] length:sizeof(float)];
}

现在尝试显示数据(显示为空白):

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

这是正确的方法吗?首先需要CGContext吗?我希望用NSData实现这一目标.

我已经注意到早期的Stack帖子:32 bit data,close but in reverse,almost worked but no NSData,color image data here,但是对于这些工作的变化并没有多少运气.谢谢你的任何建议.

解决方法

您可以使用NSBitmapImageRep来构建NSImage float-by-float.

有趣的是,其中一个初始化程序在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包含一个正确的位图格式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读