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

Objective c 如何使用Mac OS重复绘制背景图像,objective-c,macos,nsimage,nsimageview,Objective C,Macos,Nsimage,Nsimageview,我是Mac OS编程新手。因为我的原始图像很小,所以我想在背景中重复绘制图像。这是绘制图像的代码,但它似乎放大了图像,这意味着它只绘制一个图像,而不是多个图像 // overwrite drawRect method of NSView -(void)drawRect:(NSRect)dirtyRect{ [[NSImage imageNamed:@"imageName.png"] drawInRect:dirtyRect fromRect:NSZeroRect opera

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

这应该对你有用

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

}

<强>注释< /强>:您可以考虑创建<代码>后台颜色>代码>作为优化对象的一部分,因为调用频繁调用。

这对您应该适用。

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

}

<强>注释< /强>:您可以考虑创建<代码>背景颜色>代码>作为优化对象的一部分,因为调用ReScReT经常被调用。

您是否希望将图像呈现为一种模式?@ Lead Suth-Zeppelin YEP,但似乎不起作用。它在IOS中可以很好地使用这一行[UIColor WithPatternImage:[UIImage imageName:@“imageName.png”];我换了一种颜色。。但它不起作用……可能。似乎这个问题以前可能已经得到了回答。我不这么认为,因为我尝试了NSColor,但它不起作用。:)你想把图像渲染成图案吗?@lead\u the\u zeppelin是的,但似乎不起作用。它在IOS中可以很好地使用这一行[UIColor WithPatternImage:[UIImage imageName:@“imageName.png”];我换了一种颜色。。但它不起作用……可能。似乎这个问题以前可能已经得到了回答。我不这么认为,因为我尝试了NSColor,但它不起作用。:)