Repeating background image in an NSView

前端 未结 3 801
天命终不由人
天命终不由人 2021-02-01 10:28

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 initWithFram         


        
相关标签:
3条回答
  • 2021-02-01 11:04

    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.

    0 讨论(0)
  • 2021-02-01 11:05

    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.

    0 讨论(0)
  • 2021-02-01 11:20

    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;
    }
    
    0 讨论(0)
提交回复
热议问题