头文件 MyTableView.h
#import <Cocoa/Cocoa.h>
@interface MyTableView : NSTableView
{
NSImage* backgroundImage;
}
- (void)setBackgroundImage:(NSImage*)image;
- (void)clearBackgroundImage;
@end
源文件 MyTableView.m
#import "MyTableView.h"
@implementation MyTableView
-(void)awakeFromNib
{
// this is important for background images in outline views -
// use it if you don't want the scroller to cause the background to redraw
// Without it, if the user scrolls the background tries to draw at the same time (we don't want that).
//
[[self enclosingScrollView] setDrawsBackground: NO];
}
-(void)drawBackgroundImage
{
if (backgroundImage != nil)
{
NSRect visRect = [[self enclosingScrollView] documentVisibleRect];
[backgroundImage setFlipped:YES];
[backgroundImage drawInRect:NSMakeRect(visRect.origin.x, visRect.origin.y, [self frame].size.width, [self frame].size.height)
fromRect:NSMakeRect(0,0,[backgroundImage size].width, [backgroundImage size].height)
operation:NSCompositeCopy
fraction:1.0];
[backgroundImage setFlipped:NO];
}
}
- (void)drawBackgroundInClipRect:(NSRect)clipRect
{
// drawing our background image in this method does not work all by itself,
// because the clipping area has been set and not ALL the background
// will update properly. You also need to implement "drawRect" as well
//
[super drawBackgroundInClipRect:clipRect];
[self drawBackgroundImage];
}
- (void)drawRect:(NSRect)drawRect
{
[self drawBackgroundImage];
[super drawRect: drawRect];
}
// method used to set and turn on the background image, forces an update
- (void)setBackgroundImage:(NSImage*)image
{
backgroundImage = [image retain];
[self setNeedsDisplay: YES];
}
// method used to remove or clear the background image, forces an update
- (void)clearBackgroundImage
{
if (backgroundImage != nil)
{
[backgroundImage release];
backgroundImage = nil;
}
[self setNeedsDisplay: YES];
}
@end