如何使用Mac OS重复绘制背景图像

时间:2013-11-04 18:42:23

标签: objective-c macos nsimage nsimageview

我是Mac OS编程的新手。因为原始图像很小,我想在背景中重复绘制图像。这是绘制图像的代码,但它似乎放大图像,这意味着它只绘制一个图像而不是多个。

  // overwrite drawRect method of NSView
 -(void)drawRect:(NSRect)dirtyRect{
        [[NSImage imageNamed:@"imageName.png"] drawInRect:dirtyRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1];
        [super drawRect:dirtyRect];
 }

1 个答案:

答案 0 :(得分:1)

这对你有用......

// 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];

}

注意:您可能会考虑创建backgroundColor作为优化对象的一部分,因为经常会调用drawRect。