1

I am new in Mac OS programming. I would like to draw image repeatedly in background since my original image is small. Here is the code of drawing the image, but it seems enlarge the image which means it only draw one image instead of multiple.

  // overwrite drawRect method of NSView
 -(void)drawRect:(NSRect)dirtyRect{
        [[NSImage imageNamed:@"imageName.png"] drawInRect:dirtyRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1];
        [super drawRect:dirtyRect];
 }
YU FENG
  • 888
  • 1
  • 12
  • 29
  • 1
    are you looking to render the image as a pattern? – lead_the_zeppelin Nov 04 '13 at 18:45
  • @lead_the_zeppelin yep, but seems does not work. it works fine in IOS with this line [UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName.png"]]; I changed to NSColor.. but it does not work.. – YU FENG Nov 04 '13 at 18:48
  • possible [duplicate?](http://stackoverflow.com/questions/9350607/creating-pattern-on-the-fly). It seems like this question might have been answered before. – lead_the_zeppelin Nov 04 '13 at 18:54
  • I do not think so, because I tried NSColor and it does not work. :) – YU FENG Nov 04 '13 at 19:00

1 Answers1

1

This should work for you...

// overwrite drawRect method of NSView
-(void)drawRect:(NSRect)dirtyRect{
    [super drawRect:dirtyRect];

    // Develop color using image pattern
    NSColor *backgroundColor = [NSColor colorWithPatternImage:[NSImage imageNamed:@"imageName.png"]];

    // Get the current context and save the graphic state to restore it once done.
    NSGraphicsContext* theContext = [NSGraphicsContext currentContext];
    [theContext saveGraphicsState];

    // To ensure that pattern image doesn't truncate from top of the view.
    [[NSGraphicsContext currentContext] setPatternPhase:NSMakePoint(0,self.bounds.size.height)];

    // Set the color in context and fill it.
    [backgroundColor set];
    NSRectFill(self.bounds);

    [theContext restoreGraphicsState];

}

Note: You may like to consider creating backgroundColor as part of the object for optimization as drawRect is called pretty often.

Ashok
  • 6,224
  • 2
  • 37
  • 55