Macのウインドウに、砂嵐を表示する サンプルプログラム

Cocoa + Objective-C で、Macのウインドウに砂嵐を表示します。
新しい砂嵐を 30fps 間隔で、再描画するので、結果的に、砂嵐が動いているように見えます。
参考にさせていただいたコード から、そぎ落として、最低限のコードにしました。



あと、.nib ファイルをダブルクリックして、Interface Builder
を起動して、ウインドウに、NSViewを貼り付けて、クラス名を、myView にしました。

 ----  myView.h ------

#import <Cocoa/Cocoa.h>

@interface myView : NSView {
}
@end

 ----- myView.m ------

#import "myView.h"

@implementation myView
NSImage *movieImage;
NSBitmapImageRep *bitmapRep;
NSTimer *timer;

//**** initialize ****
- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
        // NSImage だけでは細かいことが出来ないので、NSBitmapImageRep も作る
		movieImage = [[[NSImage alloc] init] retain];
		bitmapRep = [[[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL  // (unsigned char **)planes 
		     pixelsWide:(int)frame.size.width		// (int)width 
		     pixelsHigh:(int)frame.size.height		// (int)height 
		     bitsPerSample:8				// (int)bps 
		     samplesPerPixel:1	// (int)spp  (3 if RGB, 4 if RGBA)
		     hasAlpha:NO	// (BOOL)alpha 
		     isPlanar:NO	// (BOOL)isPlanar 
		     colorSpaceName:NSDeviceWhiteColorSpace	// (NSString *)colorSpaceName (NSDeviceRGBColorSpace)
		     bytesPerRow:(int)frame.size.width		// (int)rowBytes (imgW*3 if RGB)
		     bitsPerPixel:8]				// (int)pixelBits (24 if RGB)
		     retain];
		
		[movieImage addRepresentation:bitmapRep ];
		[self startAnimation:nil];   // start animation 
    }
    return self;
}

// ****** NSView Drawing *********
- (void)drawRect:(NSRect)dirtyRect {
	NSPoint  point = { 0, 0 };

	[self generateRandomDotMovie];  // 新たな砂嵐を描画する

    // Drawing code here.
	[movieImage compositeToPoint:point operation:NSCompositeCopy];  //was Sover

}

// ******** write random dot to NSView *********
- (void)generateRandomDotMovie {
	static int seed=0;
	seed++;
	srandom(seed);		// seed random number generator
	int j;
	int nx = (int)([self bounds].size.width);
	int ny = (int)([self bounds].size.height);
	int npix = nx*ny;
	unsigned char *bitmapData;
	bitmapData = [bitmapRep bitmapData];		// pointer to raw bitmap data area
	for(j=0; j<npix; j++) {
		*bitmapData++ = random()&0xff;
	}
}

// ****** start animation ********
- (IBAction)startAnimation:(id)sender {
    // We schedule a timer for a desired 30fps animation rate.
    timer = [[NSTimer scheduledTimerWithTimeInterval:(1.0/30) // 30fps のタイマー駆動する
				  target:self selector:@selector(performAnimation:) userInfo:nil repeats:YES] retain];    
}


// ***** animation *******
- (void)performAnimation:(NSTimer *)aTimer {
	[self setNeedsDisplay:YES];     // NSViewに、再描画が必要なことを知らせる
}

@end


さぁ、あなたも、Cocoa + Objective-Cで、何か作りたくなってくーる。。
<はいはい


iPhoneとは、また、全然違うよね。。