macOS學習筆記(9)簡易圖片查看器

省略建工程,添加圖片以及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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章