8

我正在尝试在我的 NSView 中绘制一个重复的背景图像,我有这个到现在:

// INIT
- (id)initWithFrame:(NSRect)frame {
  if (self = [super initWithFrame:frame]) {
    self.backgroundImage = [NSImage imageNamed:@"progressBackground.pdf"];
  }

  return self;
}

// DRAW
- (void)drawRect:(NSRect)dirtyRect {
  // Draw the background
  [backgroundImage drawInRect:[self bounds]
                     fromRect:NSMakeRect(0.0f, 0.0f, backgroundImage.size.width, backgroundImage.size.height)
                    operation:NSCompositeSourceAtop
                     fraction:1.0f];
  NSLog(@"%dx%d", backgroundImage.size.width, backgroundImage.size.height);
}

但是,视图会拉伸图像以填充自身。我希望图像重复。

替代文字 (黑色笔划已经固定)

此外,发生了一些奇怪的事情,因为控制台说图像的大小等于-2109897792x0,但图像真的是32x32!怎么回事?!

有人可以帮我吗?谢谢。

4

3 回答 3

22

您可以使用+[NSColor colorWithPatternImage:]创建图案颜色,然后用该“颜色”填充背景矩形。那应该做你想要完成的事情。

于 2010-10-10T13:09:19.153 回答
17

我在这里找到了答案,以防止从底部绘制图案并在窗口调整大小时产生奇怪的效果:

http://www.mere-mortal-software.com/blog/details.php?d=2007-01-08

基本上你在drawRect中需要做的就是保存你的图形上下文状态,调用方法,绘制你的图案,然后恢复你的状态。

方法是:

- (void)drawRect:(NSRect)dirtyRect {
    NSGraphicsContext* theContext = [NSGraphicsContext currentContext];
    [theContext saveGraphicsState];
    [[NSGraphicsContext currentContext] setPatternPhase:NSMakePoint(0,[self frame].size.height)];
    [self.customBackgroundColour set];
    NSRectFill([self bounds]);
    [theContext restoreGraphicsState]; 
}

我在 init 方法中初始化了我的背景颜色模式:

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.customBackgroundColour = [NSColor colorWithPatternImage:[NSImage imageNamed:@"light-linen-texture.png"]];
    }

    return self;
}
于 2011-09-14T02:01:08.270 回答
0

RMSkinnedView在 Github 上查看!

EDIT:RMSkinnedView是一个子类,您可以在其中直接通过Interface Builder 中的用户定义的运行时属性NSView设置多个选项,包括圆角、背景颜色、背景图像图案等。

于 2013-12-29T16:43:54.813 回答