将文件打印到 NSImage 无法正常工作(可可)

发布于 2024-08-08 22:28:46 字数 526 浏览 13 评论 0原文

这可能是一个n00b问题所以我提前道歉。我是第一次使用 NSImage,基本上我需要简单地拍摄资源文件夹中的一张照片,并在单击按钮时将其显示在 NSView/NSImageWell 中。

NSImage *image = [[NSImage alloc] initWithContentsOfFile:@"tiles.PNG"];   
if ( [image isValid] ) {  
 NSImageView *view = [[NSImageView alloc] init];  
 [selection setImage:image];  
 [selection setImageScaling:NSScaleProportionally];  
}  
else {   
--- This line of code always activates meaning my image isn't valid     
}  

我唯一的猜测是我得到的图像文件路径错误,并且我已经仔细寻找访问它的正确方法。另一个猜测是我的代码错误。有人熟悉这个吗?谢谢!

This is probably a n00b question so I apologize in advance. I'm working with NSImage for the first time and basically I need to simply take a picture that is in my Resources folder, and have it display in an NSView/NSImageWell when a button is clicked.

NSImage *image = [[NSImage alloc] initWithContentsOfFile:@"tiles.PNG"];   
if ( [image isValid] ) {  
 NSImageView *view = [[NSImageView alloc] init];  
 [selection setImage:image];  
 [selection setImageScaling:NSScaleProportionally];  
}  
else {   
--- This line of code always activates meaning my image isn't valid     
}  

My only guess is that I am getting the path wrong to the image file and I have looked all over for the right way to access it. Another guess is that I have my code wrong. Anybody familiar with this? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

稚然 2024-08-15 22:28:46

我经常使用 iPhone 工作,但 initWithContentsOfFile 似乎需要完整/相对路径,我认为tiles.PNG 无法满足这一要求。

我将使用类方法 imageNamed:(NSString *)name ,它将为您搜索您的包。

I work a lot more with the iPhone, but initWithContentsOfFile seems to require a full/relative path, which I assume tiles.PNG wouldn't fulfill.

I'd use the class method imageNamed:(NSString *)name, which will search your bundle for you.

|煩躁 2024-08-15 22:28:46

您应该使用 NSBundleManger 来定位图像,如下所示:

NSBundle *mb=[NSBundle mainBundle];
NSString *fp=[mb pathForResource:@"titles" ofType:@"PNG"];
UIImage *img=[UIImage imageWithContentsOfFile:fp];

这样您就不必自己弄乱内部路径。否则,您必须拥有与最终构建的产品相关的路径,而这很难创建和维护。

You should use NSBundleManger to locate the image like so:

NSBundle *mb=[NSBundle mainBundle];
NSString *fp=[mb pathForResource:@"titles" ofType:@"PNG"];
UIImage *img=[UIImage imageWithContentsOfFile:fp];

That way you don't have to mess with internal paths yourself. Otherwise, you have to have the path relative to the final built product which is hard to create and maintain.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文