Source

Barebones CA Particles 01 / ParticleController.m

Full commit
//
//  ParticleController.m
//  particle_01
//


#import "ParticleController.h"

@interface ParticleController (Internal)
-(CGImageRef)CGImageNamed:(NSString*)name;
@end


@implementation ParticleController

-(void)awakeFromNib {
	float particleMultiplier = 40.0 / 100.0;
	
	//Create the root layer
	rootLayer = [CALayer layer];
	rootLayer.bounds = [view bounds];
	
	//Set the root layer's background color to black
	rootLayer.backgroundColor = CGColorGetConstantColor(kCGColorBlack);
	
	//Create the emitter layer
	emitter = [CAEmitterLayer layer];
	emitter.emitterPosition = CGPointMake(CGRectGetMidX(rootLayer.bounds), 
										  CGRectGetMidY(rootLayer.bounds));
	emitter.emitterMode = kCAEmitterLayerOutline;
	emitter.emitterShape = kCAEmitterLayerCircle;
	emitter.renderMode = kCAEmitterLayerAdditive;
	emitter.emitterSize = CGSizeMake(50 * particleMultiplier, 0);
	
	//Create the emitter cell
	CAEmitterCell* particle = [CAEmitterCell emitterCell];
	particle.emissionLongitude = M_PI;
	particle.birthRate = particleMultiplier * 1000.0;
	particle.lifetime = particleMultiplier;
	particle.lifetimeRange = particleMultiplier * 0.35;
	particle.velocity = 180;
	particle.velocityRange = 130;
	particle.emissionRange = 1.1;
	//particle.yAcceleration = -200;
	particle.scaleSpeed = 0.3;
	CGColorRef color = CGColorCreateGenericRGB(0.3, 0.4, 0.9, 0.10);
	particle.color = color;
	CGColorRelease(color);
	particle.contents = (id) [self CGImageNamed:@"spark.png"];
	
	//Name the cell so that it can be animated later using keypaths
	[particle setName:@"particle"];
	
	//Add the emitter cell to the emitter layer
	emitter.emitterCells = [NSArray arrayWithObject:particle] ;
	
	//Add the two emitter layers to the root layer
	[rootLayer addSublayer:emitter];
	
	//Set the view's layer to the base layer
	[view setLayer:rootLayer];
	[view setWantsLayer:YES];
	
	//Force the view to update
	[view setNeedsDisplay:YES];
}

//Return a CGImageRef from the specified image file in the app's bundle
-(CGImageRef)CGImageNamed:(NSString*)name {
	CFURLRef url = (CFURLRef) [[NSBundle mainBundle] URLForResource:name withExtension:nil];
	CGImageSourceRef source = CGImageSourceCreateWithURL(url, NULL);
	CGImageRef image = CGImageSourceCreateImageAtIndex(source, 0, NULL);
	CFRelease(source);
	return (CGImageRef)[NSMakeCollectable(image) autorelease];
}

@end