Repeating background image in an NSView

荒凉一梦 提交于 2019-12-03 05:18:09

问题


I am trying to draw a repeating background image in my NSView, I have this till now:

// 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);
}

However, the view stretches the image to fill itself. I want the image to repeat instead.

(the black strokes are fixed already)

Also, something strange happens, as the console says the size of the image equals -2109897792x0, but the image really is 32x32! WTF?!

Could someone help me, please? Thanks.


回答1:


You can create a pattern color with +[NSColor colorWithPatternImage:] and then just fill the background rectangle with that "color". That should do what you want to accomplish.




回答2:


I found the answer here to prevent patterns from drawing from the bottom and giving that weird effect when windows resize:

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

Basically all you need to do in your drawRect is to save your graphics context state, call the method, paint your pattern, then restore your state.

The method is:

- (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]; 
}

I initialized my background color pattern in the init method:

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

    return self;
}



回答3:


Check out RMSkinnedViewon Github!

EDIT: RMSkinnedView is a NSView subclass where you can set up several options, including rounded corners, background color, background image pattern, etc., directly via the User Defined Runtime Attributes in the Interface Builder.



来源:https://stackoverflow.com/questions/3900392/repeating-background-image-in-an-nsview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!