我目前正在尝试创建一个访问文件夹并随机加载图像并在其窗口中显示它们的简单应用程序。 正如所料,我正在努力奋斗。
我需要文件:
.h为空,.m包含所有代码。
#import "AppDelegate.h"
@interface AppDelegate ()
@property (strong) NSImage *image;
@property (weak) IBOutlet NSWindow *window;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
NSRect frame = [_window frame];
NSView *view = [[NSView alloc] initWithFrame: frame];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"pathtoimage" ofType:@"jpg"];
_image = [[NSImage alloc] initWithContentsOfFile:imagePath];
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Insert code here to tear down your application
}
@end
那么我现在如何将视图设置到窗口,然后如何将图像绘制到视图中?
编辑: 将代码更改为此内容,除了空窗口外,仍然没有显示任何内容。
#import "AppDelegate.h"
@interface AppDelegate ()
@property (weak) IBOutlet NSWindow *window;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
NSRect frame = [_window frame];
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"/Users/Me/Documents/Me/Art/picturename" ofType:@"png"];
NSImage *image = [[NSImage alloc] initWithContentsOfFile:imagePath];
NSImageView *myImage = [[NSImageView alloc] init];
[myImage setFrame:frame];
[myImage setImage:image];
[self.window.contentView addSubview:myImage];
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Insert code here to tear down your application
}
@end
EDIT2:
#import "AppDelegate.h"
@interface AppDelegate ()
@property (weak) IBOutlet NSWindow *window;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
NSRect frame = [_window frame];
//NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"doorTech" ofType:@"jpg"];
NSImage *image = [[NSImage alloc] initWithContentsOfFile:@"/Users/Adrian/Documents/Adrian/Art/desertMovie.jpg"];
if (image == nil) {
NSLog(@"Image is nil");
} else {
NSLog(@"Image is not nil");
}
NSImageView *myImage = [[NSImageView alloc] init];
[myImage setFrame:frame];
[myImage setImage:image];
[self.window.contentView addSubview:myImage];
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Insert code here to tear down your application
}
@end