Setting the background of a custom view with an image results in a black background

白昼怎懂夜的黑 提交于 2020-01-17 08:55:20

问题


I have a problem setting the background of my subclassed NSView called TitlebarView. I want to use an image as a background via colorWithPattternImage, but the result is a black background not the image i gave the method as a parameter.

Here's my code of TitlebarView:

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        NSString* pathToTitlebarBGImage = [[NSBundle mainBundle] pathForResource:@"titlebar_bg" ofType:@"png" inDirectory:@"Resources/gui_images"];
        NSLog(@"path to titlebar bg image: %@", pathToTitlebarBGImage);
        //    NSString* pathToTitlebarBGImage = @"Resources/gui_images/titlebar_bg.png";
        self.titlebarBGImage = [NSImage imageNamed:pathToTitlebarBGImage];
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    [super drawRect:dirtyRect];
    [[NSColor colorWithPatternImage:self.titlebarBGImage] setFill];
//    [[NSColor redColor] setFill];
    NSRectFill(dirtyRect);
}

titlebarBGImage is a properly set property in the header files.
If I use the line with redColor I get the red colored view, so the code is working to some degree. For all I could find in the documentation an on stackoverflow this should actually work as intended. What am I missing here?

This is isolated problem of my overall question found here


回答1:


imageNamed: takes a file name, not a path name, and searches for the file name in the bundle. If you wish to load an image from a path use initWithContentsOfFile:. See the NSImage documentation.



来源:https://stackoverflow.com/questions/22681956/setting-the-background-of-a-custom-view-with-an-image-results-in-a-black-backgro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!