1

我是 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];
 }
4

1 回答 1

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 经常被调用。

于 2013-11-04T19:15:49.323 回答