Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

displaying an image in cocoa

Tags:

image

cocoa

I am totally new at this, but here goes: I want to press a button in my application, and have an image display (I am planning to read it off of a camera, but to start with, I will open a .TIF file.) However, within the interface builder, I can make buttons within an NSObject object, but the literature makes it sound like I need to make an NSView object to display a file. The problem is, when I do this, the NSObject object does not seem to talk to the NSView object. I am trying to do something like:

    NSString *inFilePath;
    inFilePath = @"/Volumes/Data/Temp/Smiles.tiff";
    NSImage *TestImage = [[NSImage alloc] initWithContentsOfFile:inFilePath];
    [MyView setImage:TestImage];

Here, MyView is the NSView object. I get warnings that MyView may not respond to setImage. I have tried to define an IBOutlet within the NSObject object, and although I can connect it within the interface builder, console gives me the error:

unrecognized selector sent to class 0x1e080

So, it's not clear what the next step is. Is there an easy way to get two different objects to "talk to" each other? Thanks

like image 812
monty wood Avatar asked Mar 08 '11 20:03

monty wood


1 Answers

You want an NSImageView object. In the Interface Builder library this is called an Image Well, but you can configure it so that it doesn't have a bezel.

NSImageView is a subclass of NSView that is optimised for displaying images.

In your header (.h) file, you should have something like this:

 @interface MyController : NSObject
{
    //this declares an outlet so you can hook up the 
    //image view in Interface Builder
    IBOutlet NSImageView* imageView;
}
@end

And in your implementation (.m) file:

@implementation MyController

//called once the nib is loaded and all outlets are available
- (void)awakeFromNib
{
    NSString *inFilePath = @"/Volumes/Data/Temp/Smiles.tiff";
    NSImage *testImage = [[NSImage alloc] initWithContentsOfFile:inFilePath];
#if !__has_feature(objc_arc)
  [testImage autorelease];
#endif
    //imageView is your outlet
    [imageView setImage:testImage];
}

@end

In Interface Builder you should hook up the imageView outlet of your class to point to the NSImageView you placed on your view.

like image 73
Rob Keniger Avatar answered Sep 19 '22 14:09

Rob Keniger