Here's my code so far (in the draw rect):
// Drawing code here.
NSLog(@"%@", [[NSBundle mainBundle] pathForResource:@"NoiseBGMainView" ofType:@"jpg"]);
NSURL *pathToBGImage = [开发者_高级运维[NSURL alloc] initWithString:[[NSBundle mainBundle] pathForResource:@"NoiseBGMainView" ofType:@"jpg"]];
NSImage *NoiseBGMainView = [[NSImage alloc] initWithContentsOfURL:pathToBGImage];
[NoiseBGMainView drawInRect:[self bounds] fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1];
And the image doesn't draw... I don't know what's wrong.
Why not just use [NSImage imageNamed:@"NoiseBGMainView.jpg"]
instead? That will give you an NSImage
of your picture (if it can find it), and nil
if it can't. NSLog
what the results of that call are, then come and report back on whether it's logging (null)
or not.
You can draw an NSImage into an NSView without writing any drawing code by attaching an NSImageView to your view and setting your image resource as the NSImageView's image. (NSImageView handles all the drawing).
If your custom NSView is loaded from a nib, you don't need any setup code either - just make the appropriate NSView-NSImageView-NSImage (resource) connections with Interface Builder.
NSURL *pathToBGImage = [[NSURL alloc] initWithString:[[NSBundle mainBundle] pathForResource:@"NoiseBGMainView" ofType:@"jpg"]];
This is wrong. -[NSURL initWithString:]
takes a string version of a URL, such as http://apple.com/, not a pathname.
Because you didn't pass a URL, the URL will be a relative URL, but a relative URL needs a base. The URL is a valid object, but doesn't lead anywhere. This, in turn, causes initWithContentsOfURL:
to return nil
(because you tried to load an image from a relative URL with no base). You then try to tell the image to draw, but you don't have an image, so nothing happens.
You want initFileURLWithPath:
. (Or the class method fileURLWithPath:
, with which you won't have to release the URL later.)
精彩评论