0

So I'm trying to set the background of a view as an image, and I read in another thread that to avoid repeating the image, one should use NSImage drawInRect:fromRect:operation:fraction: rather than NSColor colorWithPatternImage: However, when I use the former the image doesn't draw in the view, while it works with the latter (but repeats, which I don't want). Is there something I'm missing here? The image is in the Images.xcassets folder and I implemented both methods as suggested in the other thread here: How to make NSView's background image not repeat?

Here's my code:

#import "OrangeBGView.h"

@implementation OrangeBGView

- (void)drawRect:(NSRect)dirtyRect
{
    [[NSColor blueColor] setFill];//To easily see if image isn't loading
    NSRectFill(dirtyRect);

    [[NSColor colorWithPatternImage:[NSImage imageNamed:@"orangeGradientBGWithTopEdgeShadow.png"]] setFill];//Working
//    [[NSImage imageNamed:@"orangeGradientBGWithTopEdgeShadow.png"] drawInRect:dirtyRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1];//Not working
    NSRectFill(dirtyRect);

}

@end
Community
  • 1
  • 1
Matt Cooper
  • 2,042
  • 27
  • 43
  • there is no point in calling super here since you are clobbering whatever it does with your fill. Show us the code where you try using `NSImage` and `drawInRect:` please. – Brad Allred Dec 01 '13 at 20:27
  • @BradAllred Okay, thanks. Took out the super. The `drawInRect:` line is the commented line below the `colorWithPatternImage:` so that code would just be the same thing but with the `colorWithPatternImage:` line commented and the `drawInRect:` line active. – Matt Cooper Dec 01 '13 at 20:54

1 Answers1

0

This was a simple oversight on my part. the drawInRect:fromRect:operation:fraction: was working fine, but I left in the last NSRectFill(dirtyRect) line, which essentially painted over the image I was drawing. This code now works:

#import "OrangeBGView.h"

@implementation OrangeBGView

- (void)drawRect:(NSRect)dirtyRect
{
    [[NSColor blueColor] setFill];//To easily see if image isn't loading
    NSRectFill(dirtyRect);

    [[NSImage imageNamed:@"orangeGradientBGWithTopEdgeShadow.png"] drawInRect:dirtyRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1];
}

@end
Matt Cooper
  • 2,042
  • 27
  • 43