I am looking for a perfect solution to set a background image for a window in a cocoa application. I haven't found a solution to this, I am new in objective c, so please anyone help me...
Michael Vannorsdel suggests sublassing NSView
for the purpose, and I quote:
You'd really be better off making an NSView subclass and having it draw the image you want in drawRect:.
- (void)awakeFromNib
{
myImage = [[NSImage alloc] init....
[self setNeedsDisplay:YES];
}
- (void)drawRect:(NSRect)rect
{
NSSize isize = [myImage size];
[myImage drawInRect:[self bounds] fromRect:NSMakeRect(0.0, 0.0,
isize.width, isize.height) operation: NSCompositeCopy fraction:1.0];
}
Read that whole thread on cocoabuilder, it's quite instructive.
A window in Cocoa has a root-level view called the "content view". This is the view that contains all the others in a window. By default, it's just a plain, blank NSView
. But you could easily create your own custom NSView
subclass, override the drawRect:
method to draw your background image, and use that for your custom view.
However, it might just be easier to use a plain old NSImageView
. The advantage of this is that you can set, for example, autosizing behavior to keep the image pinned to one corner (try this with Installer.app by resizing the installer window). You would also be able to make it semi-opaque so that the background shows through a bit. (Again, I'm thinking of Installer.app; your app could be totally different)
Hope that gets you going in the right direction!
Dave Batton wrote a very thorough article on this in his Living the Life blog at
http://www.mere-mortal-software.com/blog/details.php?d=2007-01-08
including full sample code.