我想在我的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