Repeating background image in an NSView

user142019 picture user142019 · Oct 10, 2010 · Viewed 8.7k times · Source

I am trying to draw a repeating background image in my NSView, I have this till now:

// INIT
- (id)initWithFrame:(NSRect)frame {
  if (self = [super initWithFrame:frame]) {
    self.backgroundImage = [NSImage imageNamed:@"progressBackground.pdf"];
  }

  return self;
}

// DRAW
- (void)drawRect:(NSRect)dirtyRect {
  // Draw the background
  [backgroundImage drawInRect:[self bounds]
                     fromRect:NSMakeRect(0.0f, 0.0f, backgroundImage.size.width, backgroundImage.size.height)
                    operation:NSCompositeSourceAtop
                     fraction:1.0f];
  NSLog(@"%dx%d", backgroundImage.size.width, backgroundImage.size.height);
}

However, the view stretches the image to fill itself. I want the image to repeat instead.

alt text (the black strokes are fixed already)

Also, something strange happens, as the console says the size of the image equals -2109897792x0, but the image really is 32x32! WTF?!

Could someone help me, please? Thanks.

Answer

DarkDust picture DarkDust · Oct 10, 2010

You can create a pattern color with +[NSColor colorWithPatternImage:] and then just fill the background rectangle with that "color". That should do what you want to accomplish.