省略建工程,添加图片以及ui设计部分。
#import <Cocoa/Cocoa.h>
@interface ViewController : NSViewController
{
IBOutlet NSImageView *imageview;
NSArray * imagePaths;//图像所在路径的引用
NSMutableArray *images;//图像的引用
int count;
IBOutlet NSTextField *num;
}
-(IBAction)nextImage:(id)sender;
-(IBAction)beforeImage:(id)sender;
-(IBAction)numImage:(id)sender;
@end
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)setRepresentedObject:(id)representedObject {
[super setRepresentedObject:representedObject];
// Update the view, if already loaded.
}
-(void)awakeFromNib
{
NSBundle * mainBundle = [NSBundle mainBundle];
//引用图像的路径
// NSString * path = [mainBundle pathForResource:@"Abstract 1" ofType:@"png"];//查看文件名为Abstract.png的图片
// NSImage * image = [[NSImage alloc] initWithContentsOfFile:path];
//获得文件包的引用,在文件包中默认文件夹resource查询png后缀的文件,返回一个数组
imagePaths = [mainBundle pathsForResourcesOfType:@"png" inDirectory:nil];
//保留引用
[imagePaths retain];
count = 0;
//用数组第一个元素对应的文件内容初始化一个nsimage类,得到一个实例
NSImage * image =[[NSImage alloc] initWithContentsOfFile:[imagePaths objectAtIndex:count]];
//显示图片,然后销毁这个实例
[imageview setImage:image];
[image release];
}
/*
//用图像的引用来显示图片,提高性能
-(void)awakeFromNib
{
NSBundle * mainBundle = [NSBundle mainBundle];
NSArray * imagePaths = [mainBundle pathsForResourcesOfType:@"png" inDirectory:nil];
images = [[NSMutableArray alloc] init];
int mycount = [imagePaths count];
int i;
for(i=0;i<mycount;i++)
{
NSImage * image = [[NSImage alloc] initWithContentsOfFile:[imagePaths objectAtIndex:i]];
[images addObject:image];
[image release];
}
count = 0;
[imageview setImage:[images objectAtIndex:count]];
}
-(IBAction)nextImage:(id)sender
{
count++;
if (count==[images count]) {
count=0;
}
[imageview setImage:[images objectAtIndex:count]];
}
*/
//
-(IBAction)nextImage:(id)sender
{
count ++;
if(count == [imagePaths count])
{
count = 0;
}
NSImage * image = [[NSImage alloc] initWithContentsOfFile:[imagePaths objectAtIndex:count]];
[imageview setImage:image];
[image release];
}
-(IBAction)beforeImage:(id)sender
{
count --;
if(count < 0)
{
count = count + (int)[imagePaths count];
}
NSImage * image = [[NSImage alloc] initWithContentsOfFile:[imagePaths objectAtIndex:count]];
[imageview setImage:image];
[image release];
}
//加一个输入框,输入数字,查看特定序号的图片
-(IBAction)numImage:(id)sender
{
count=[num intValue];
if((count < 0)||(count > [imagePaths count]))
{
exit(-1);
}
NSImage * image = [[NSImage alloc] initWithContentsOfFile:[imagePaths objectAtIndex:count]];
[imageview setImage:image];
[image release];
}
//
@end