Cocoa で画像を扱うときは、NSImage を使うでしょ。NSImage は、その内容をあらわす NSImageRep をいくつか持っている。NSImageRep には、ビットマップをあらわす NSBitmapImageRep とか、PDF をあらわす NSPDFImageRep とかがあるんだ。じゃあ、たとえばベジェで描くのを NSImageRep としたいときとかは?
そういうときに使えるのが NSCustomImageRep だ。このクラスを使えば、NSImageRep の描画ルーチンを自分で設定できるんだ。
Application Kit/NSCustomImageRep.h
- (id)initWithDrawSelector:(SEL)aMethod delegate:(id)anObject;
これを使うと、自前の描画ルーチンを設定できる。NSImage が画像の表示が必要になると、ここで設定したセレクタを呼び出すんだ。そのときに、好きな絵を描いてやればいい。
(sample)
- (id)initWithFrame:(NSRect)frame
{
NSImage* image;
NSCustomImageRep* customRep;
self = [super initWithFrame:frame];
if(self) {
image = [[NSImage alloc] initWithSize:rect.size];
customRep = [[NSCustomImageRep alloc]
initWithSelector:@selector(drawImage:) delegate:self];
[image addRepresentation:customRep];
[customRep release];
}
return self;
}
- (void)drawImage:(NSCustomImageRep*)customRep
{
// 独自の描画処理
}
このサンプルでは、まず NSImage のインスタンスを作る。そして、その representation として、NSCustomImageRep を指定してるんだ。 NSCustomImageRep は、selector として self の drawImage: を指定している。
image が描かれるとき、drawImage: が呼び出されるんだ。この中で好きな図形を描いてくれ。