一种相当简单的方法是使用自定义 NSView 子类作为背景视图。在它的 -drawRect: 方法中,编写代码来获取图像并重复绘制它以填充视图的边界。执行此操作的算法非常简单。从左上角(或任何角落)开始,绘制图像,然后将 x 位置增加图像的宽度,然后再次绘制。当 x 位置超过视图的最大 x 坐标时,将 y 增加图像的高度并绘制下一行,依此类推,直到你填满整个东西。这应该可以解决问题:
@interface TiledBackgroundView : NSView
@end
@implementation TiledBackgroundView
- (void)drawRect:(NSRect)dirtyRect
{
NSRect bounds = [self bounds];
NSImage *image = ...
NSSize imageSize = [image size];
// start at max Y (top) so that resizing the window looks to be anchored at the top left
for ( float y = NSHeight(bounds) - imageSize.height; y >= -imageSize.height; y -= imageSize.height ) {
for ( float x = NSMinX(bounds); x < NSWidth(bounds); x += imageSize.width ) {
NSRect tileRect = NSMakeRect(x, y, imageSize.width, imageSize.height);
if ( NSIntersectsRect(tileRect, dirtyRect) ) {
NSRect destRect = NSIntersectionRect(tileRect, dirtyRect);
[image drawInRect:destRect
fromRect:NSOffsetRect(destRect, -x, -y)
operation:NSCompositeSourceOver
fraction:1.0];
}
}
}
}
@end