Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...