NSColor colorWithPatternImage:Vs. NSImage drawInRect:fromRect:operation:fraction:

时间:2013-12-01 19:23:22

标签: objective-c cocoa nsview nsimage

所以我试图将视图的背景设置为图像,我在另一个线程中读到,为了避免重复图像,应该使用NSImage drawInRect:fromRect:operation:fraction:而不是NSColor colorWithPatternImage:但是当我使用前者时,图像不会在视图中绘制,而它与后者一起使用(但重复,我不想要)。我有什么东西在这里失踪吗?图像位于Images.xcassets文件夹中,我按照其他线程中的建议实现了这两种方法:How to make NSView's background image not repeat?

这是我的代码:

#import "OrangeBGView.h"

@implementation OrangeBGView

- (void)drawRect:(NSRect)dirtyRect
{
    [[NSColor blueColor] setFill];//To easily see if image isn't loading
    NSRectFill(dirtyRect);

    [[NSColor colorWithPatternImage:[NSImage imageNamed:@"orangeGradientBGWithTopEdgeShadow.png"]] setFill];//Working
//    [[NSImage imageNamed:@"orangeGradientBGWithTopEdgeShadow.png"] drawInRect:dirtyRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1];//Not working
    NSRectFill(dirtyRect);

}

@end

1 个答案:

答案 0 :(得分:0)

这对我来说是一个简单的疏忽。 drawInRect:fromRect:operation:fraction:工作正常,但我离开了最后NSRectFill(dirtyRect)行,它基本上描绘了我正在绘制的图像。此代码现在有效:

#import "OrangeBGView.h"

@implementation OrangeBGView

- (void)drawRect:(NSRect)dirtyRect
{
    [[NSColor blueColor] setFill];//To easily see if image isn't loading
    NSRectFill(dirtyRect);

    [[NSImage imageNamed:@"orangeGradientBGWithTopEdgeShadow.png"] drawInRect:dirtyRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1];
}

@end