1

我对为什么这段代码不显示任何图像感到困惑:

在应用委托中:

- (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

蓝色图像视图.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 正在触发。但是没有图像显示在窗口中。

4

1 回答 1

5

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

于 2011-01-09T02:42:03.257 回答