Frage

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];
 }
War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top