Cocoa - 让简单的NSImageView工作

时间:2011-01-09 02:34:28

标签: cocoa nsimageview

我很困惑为什么这段代码不显示任何图片:

在app delegate中:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    NSRect rect = window.frame;
    rect.origin.x = 0;
    rect.origin.y = 0;
    BlueImageView *blueImageView = [[BlueImageView alloc]initWithFrame:rect];
    window.contentView = blueImageView; // also tried [window.contentView addSubview: blueImageView];
}

BlueImageView.h:

@interface BlueImageView : NSImageView {
}
@end

BlueImageView.m:

@implementation BlueImageView

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setImage: [NSImage imageNamed:@"imagefile.png"]];
        NSAssert(self.image, @"");
        NSLog (@"Initialized");
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
}

@end  

文件imagefile.png存在。 NSAssert不会导致异常。 NSLog正在解雇。但是窗口中没有图像显示出来。

1 个答案:

答案 0 :(得分:5)

调用drawRect:方法绘制视图,并立即返回实现。要让NSImageView为您绘制图像,请在drawRect:的实现中调用[super drawRect:dirtyRect];。如果您不打算在drawRect:中进行任何其他绘图,只需删除该方法以加快绘图速度。