我想在我的Cocoa mac应用程序的简单平铺图案中的NSView drawRect中绘制NSImage。一种方法是使用drawInRect多次绘制一个循环来绘制该图像:fromRect:operation:fraction:在Cocoa中的平铺图案中绘制图像
是否有更直接的方法?
我想在我的Cocoa mac应用程序的简单平铺图案中的NSView drawRect中绘制NSImage。一种方法是使用drawInRect多次绘制一个循环来绘制该图像:fromRect:operation:fraction:在Cocoa中的平铺图案中绘制图像
是否有更直接的方法?
NSColor* myColor = [NSColor colorWithPatternImage:myImage];
[myColor set];
// then treat it like you would any other color, e.g.:
NSFillRect(myRect);
有colorWithPatternImage的内存泄漏问题:在最近的iOS版本中修复? – 2012-06-29 05:33:28
Kurt Revis的回答是最简单的方法。如果您需要更多控制图像平铺的方式(您想缩放,旋转或翻译它),则可以使用CGContextDrawTiledImage
。您将需要get a CGImageRef
for the NSImage
,你将需要current NSGraphicsContext
的get the CGContextRef
。
梦幻般的答案,谢谢。 – 2012-03-01 06:54:42
您需要像库特指出的那样使用图案图像,但并不是那么简单。图案图像使用窗口的原点作为原点,所以如果调整窗口大小,图案将移动。
您需要根据视图在窗口中的位置来调整当前图形上下文中的模式阶段。我使用的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
你会使用这样的:
-(void) drawRect: (NSRect)dirtyRect
{
[self rk_drawPatternImage:[NSColor colorWithPatternImage:yourImage] inRect:self.bounds];
}
见http://stackoverflow.com/q/1125230/643383一对夫妇好这个问题的答案。 – Caleb 2012-02-20 05:59:17
不是那个问题的重复,因为这一个是关于可可,而不是可可触摸。 – 2012-02-20 06:05:47
同意。这很重要,因为在iOS中,Windows很少重新调整大小,但在Mac上这是很常见的情况。由于模式原点的计算方式,窗口大小调整会影响模式绘制。 – 2012-02-20 10:05:46