tags:

views:

203

answers:

2

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!

+3  A: 

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.

refulgentis
A: 

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.

TechZen
Note he is using NSImage/NSImageWell, which aren't available on the iPhone, so he must be on a Mac and therefore not have access to UIKit, and there not have access to UIImage.Also, UIImage/NSImage *img = [UIImage imageNamed:@"titles.PNG"] will accomplish the same as the above code and be slightly clearer.
refulgentis
Yes I am writing this for MAC, not iPhone. I think the code is right but my image isn't appearing. Do I have to make the ImageWell a custom class, with a subclass of NSView? I simply dragged an Imagewell from IB and called it "preview" and referenced it after declaring it in my .h file. The code works now because if [image isValid] is satisfied, but still no image prints to my view :(
Brian
It doesn't matter that you're on a Mac. I just slapped that code in because I had it on hand. The principle is the same. If the file is in the resource folder, use NSBundle to find it's path. You can also slap in NSFileManager's `fileExistsAtPath:` to make sure the file is at the path returned by NSBundle.
TechZen
Yeah I actually stuck with NSBundle because I heard using imageNamed: can oftentimes result in crashes and is less reliable. My issue still remains tho - the argument is saying I have a valid image but it's not printing to the NSImage. Do I need a custom class with a subview? Am I not declaring something? I literally do [selection setImage:image] and nothing displays.
Brian