开发者

NSScrollView background image in Lion

I'm working on a Mac application with an NSScrollView, and I want the NSScrollView to have a custom background image. I used this code in the custom documentView NSView subclass:

- (void)drawRect:(NSRect)rect {
    [[NSColor colorWithPatternImage:[NSImage imageNamed:@"wood.jpg"]] set];
    NSRectFill(rect);
}

That displays a pattern image as a background for the documentView.

But now in Mac OS X Lion, the NSScrollView bounces when scrolling further than possible, showing ugly white space. How can I make the white space also being cove开发者_如何学Cred by the background image?


Instead of overriding drawRect:, use the scroll view's setBackgroundColor: method, passing the NSColor you created with the pattern image.


You should subclass use NSScrollView setBackgroundColor, but then you should subclass NSClipView like this to pin the texture origin to the top:

@implementation MYClipView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }

    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
  if (self.drawsBackground)
  {
    NSGraphicsContext* theContext = [NSGraphicsContext currentContext];
    [theContext saveGraphicsState];

    float xOffset = NSMinX([self convertRect:[self frame] toView:nil]);
    float yOffset = NSMaxY([self convertRect:[self frame] toView:nil]);
    [theContext setPatternPhase:NSMakePoint(xOffset, yOffset)];
    NSColor* color = self.backgroundColor;
    [color set];
    NSRectFill([self bounds]);
    [theContext restoreGraphicsState]; 
  }  
  // Note: We don't call [super drawRect:dirtyRect] because we don't need it to draw over our background. 
}

+ (void)replaceClipViewInScrollView:(NSScrollView*)scrollView 
{
  NSView* docView = [scrollView documentView]; //[[scrollView documentView] retain]; 
  MYClipView* newClipView = nil;
  newClipView = [[[self class] alloc] initWithFrame:[[scrollView contentView] frame]]; 
  [newClipView setBackgroundColor:[[scrollView contentView] backgroundColor]];
  [scrollView setContentView:(NSClipView*)newClipView]; [scrollView setDocumentView:docView];
//  [newClipView release]; 
//  [docView release]; 
}
@end

And call + (void)replaceClipViewInScrollView:(NSScrollView*)scrollView with the NSScrollView instance.


Put your drawRect code in an NSScrollView subclass. In IB, change the NSScrollView to use your custom subclass instead of NSScrollView. Also make sure to uncheck Draw Background in the scroll view's attributes inspector.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜