macOS/iOS API解説

iOS , Mac アプリケーション開発のために使われる主要フレームワークの日本語情報です。2010年代に書かれた内容です。今後更新はありません。

目次

initWithContentsOfFile:

画像ファイルを開いてNSImageを作ります
-(id)initWithContentsOfFile:(NSString *)filename:

解説

画像ファイルを開いてNSImageを作ります。

  • initByReferencingFileと違い、ファイルを開けてデータから一つ以上の画像表示内容(imageRep)を作ります。

ファイル名は拡張子を含む絶対パス、または相対パスです。
初期設定で扱うことの出来るファイル形式はTIFF,GIF,jpg,pdf.pict,epsです。
初期化できなければnilを返します。

返り値

( id )

画像

引数

( NSString * )filename

画像ファイル名

フレームワーク

ApplicationKit

クラス

NSImage

Instance Methods

使用可能

10.0

参照

例文

#import "SetImage.h"

@implementation SetImage

- (IBAction)set:(id)sender
{
    //開けるファイル拡張子の配列
    NSArray      *imgTypes    = [ NSArray arrayWithObject : @"tiff" ];
    //OpenPanelを作る
    NSOpenPanel  *opImage       = [ NSOpenPanel openPanel ];
    //Imageを作る
    NSImage      *img;
    //OpenPanelの結果のボタン番号
    int		  opRet;
     
        //OpenPanelでファイル選択   
    opRet = [ opImage runModalForDirectory : NSHomeDirectory() //どこのディレクトリを出すか
                                     file : @"Pictures" //どのどのファイルを選択しておくか
                                    types : imgTypes ];//選べるファイルタイプ

    if ( opRet == NSOKButton ) {  // OPENPanelのボタンがOKなら
        //NSImageを作ってファイルから読み込む
        img = [ [ NSImage alloc ] 
                          initWithContentsOfFile: [ opImage filename ] ];
        //レシーバimage(NSImageView)にimgをセットする
        [image setImage : img ];
    }
}

@end