在Cocoa中以平铺图案绘制图像

Ama*_*der 2 macos cocoa objective-c

我想在我的Cocoa mac应用程序中以简单的tile模式在NSView drawRect中绘制一个NSImage.一种方法是使用drawInRect编写一个循环来多次绘制此图像:fromRect:operation:fraction:

有更直接的方法吗?

Rob*_*ger 9

你需要像Kurt所指出的那样使用模式图像,但并不像那样简单.图案图像使用窗口的原点作为原点,因此如果调整窗口大小,图案将移动.

您需要根据视图在窗口中的位置调整当前图形上下文中的模式阶段.我在NSView上使用这个类别:

@implementation NSView (RKAdditions)
- (void)rk_drawPatternImage:(NSColor*)patternColor inRect:(NSRect)rect
{
    [self rk_drawPatternImage:patternColor inBezierPath:[NSBezierPath bezierPathWithRect:rect]];
}

- (void)rk_drawPatternImage:(NSColor*)patternColor inBezierPath:(NSBezierPath*)path
{
    [NSGraphicsContext saveGraphicsState];

    CGFloat yOffset = NSMaxY([self convertRect:self.bounds toView:nil]);
    CGFloat xOffset = NSMinX([self convertRect:self.bounds toView:nil]);
    [[NSGraphicsContext currentContext] setPatternPhase:NSMakePoint(xOffset, yOffset)];

    [patternColor set];
    [path fill];
    [NSGraphicsContext restoreGraphicsState];
}

@end
Run Code Online (Sandbox Code Playgroud)

你会这样使用它:

-(void) drawRect: (NSRect)dirtyRect
{
    [self rk_drawPatternImage:[NSColor colorWithPatternImage:yourImage] inRect:self.bounds];
}
Run Code Online (Sandbox Code Playgroud)


Kur*_*vis 6

NSColor* myColor = [NSColor colorWithPatternImage:myImage];
[myColor set];
// then treat it like you would any other color, e.g.:
NSRectFill(myRect);
Run Code Online (Sandbox Code Playgroud)


rob*_*off 5

Kurt Revis的回答是最简单的方法.如果您需要更多地控制图像的平铺方式(您希望缩放,旋转或平移图像),则可以使用CGContextDrawTiledImage.您将需要得到CGImageRefNSImage,你将需要获得CGContextRef的的电流NSGraphicsContext.