【问题标题】:Getting the Size of a NSImage allocated with NSData获取使用 NSData 分配的 NSImage 的大小
【发布时间】:2011-06-01 02:34:04
【问题描述】:
NSImage *testImages;
NSURL *testImageUrl = [NSURL URLWithString:@"file:///foo/testImage.png"];
NSData *imageData = [testImageUrl resourceDataUsingCache:NO];
testImages = [[NSImage alloc] initWithData:imageData ];

如何获取 testImages 的 NSSize。在调试器中,我可以从 _NSSize 属性中读取它,但 [testImages size] 返回 (0,0)

在进行各种转换之前,我需要确定它是横向图像还是纵向图像。

这有效,但我不知道为什么?

NSArray *representation = [testImages representations];
NSImageRep *repOne = [representation objectAtIndex:0];
int width = [repOne pixelsWide];
return width;

【问题讨论】:

  • -[NSURL resourceDataUsingCache:] 在 Mac OS X v10.4 中已弃用。你的目标操作系统是什么?
  • 你检查过testImages-initWithData:之后是否是nil吗?

标签: iphone objective-c cocoa macos


【解决方案1】:

NSImage 类中,我们确实有属性,它为我们提供NSImage 中图像的大小。

- (NSSize)size
   NSSize size = testImages.size;

【讨论】:

  • 为了准确起见,NSImage中没有size声明的属性。
  • NSIamge 和 UIImage 都有一个 size 属性。 @Bavarious,你在说什么?
  • @Black 我是说声明的属性与 getter(以及可选的 setter)方法不同。
  • 我仍然认为自己是 Objective-C 的新手,所以我不确定你在说什么?但是看着NSImage 我看到了 - (NSSize)size 方法。对于UIImage,我看到了 size 属性。
  • @Black 官方文档明确指出了“x”何时是声明的属性,而NSImage 中的size 并非如此。头文件也是另一个信息来源——@interface NSImage… 中没有@property … size;。从 Objective-C 运行时的角度来看,NSImage 中声明的属性的枚举不会列出 size — 实际上,它不会列出任何属性。
【解决方案2】:

"...但是 [testImages size] 返回 (0,0)"

始终考虑是否在您的代码中的某个位置,某个方法或调用在您未预料到的地方返回了nil。然后沿着你的方式备份代码,找出你的代码(或你的假设)出错的地方。

NSURL *testImageUrl = [NSURL URLWithString:@"file:///foo/testImage.png"];
NSData *imageData = [testImageUrl resourceDataUsingCache:NO];
NSImage *testImages = [[NSImage alloc] initWithData:imageData ];
NSSize size = [testImages size];

如果由于某种原因URLWithString: 调用失败,它将返回nil。将-resourceDataUsingCache: 消息发送到nil 基本上会导致nil(它只是被忽略)。尝试使用为数据参数传入的nil 创建NSImage 将返回nil。并且将-size 消息发送到nil 基本上会导致nil,其大小等于{0, 0}

所以,请仔细检查以确保您的消息不只是被发送到 nil。

还有一点需要注意的是,在创建基于文件的NSURLs 时通常使用+fileURLWithPath:,在创建其他类型的URL 时通常使用+URLWithString:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-16
    • 2011-08-11
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    • 2013-09-05
    相关资源
    最近更新 更多