Hi there,
I'm somewhat new to objective-c/core graphics, but I'm curious if after initializing and calling the drawRect routine, would it be possible to change the color of the blocks dynamically without destroying them? I believe my issue(s) are mainly to do with the context, but I'm unsure if the inputColor member can be changed past initialization. My function updateColor() is below and would be called when collision is detected on a block. Everything else is verbatim of the CH6 project. Any help or advice considering would be highly appreciated.
Thanks,
J
Code:
- (id)initWithFrame:(CGRect)frame color:(int) inputColor;
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.color = inputColor;
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
float viewWidth, viewHeight;
viewWidth = self.bounds.size.width;
viewHeight = self.bounds.size.height;
//Get the drawing context
CGContextRef context = UIGraphicsGetCurrentContext();
//define a rect in the shape of a block
CGRect blockRect = CGRectMake(0, 0, viewWidth, viewHeight);
//define a path using the rect
UIBezierPath* path = [UIBezierPath bezierPathWithRect:blockRect];
//set the line width of the path
path.lineWidth = 0.0;
//define a gradient to use to fill the blocks
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 0.0, 0.0, 0.0, 1.0, //start color
1.0, 1.0, 1.0, 1.0 }; //end color
//determine gradient color based on color property
switch (self.color) {
case RED_COLOR:
//red block
components[0] = 1.0;
break;
case GREEN_COLOR:
//red block
components[1] = 1.0;
break;
case BLUE_COLOR:
//red block
components[2] = 1.0;
break;
default:
break;
}
CGGradientRef myGradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, sizeof(locations)/sizeof(CGFloat));
CGContextDrawLinearGradient(context, myGradient, CGPointMake(0, 0), CGPointMake(viewWidth, 0), 0);
//clean up the color space and gradient
CGColorSpaceRelease(colorSpace);
CGGradientRelease(myGradient);
//stroke the path
[path stroke];
}
-(void)updateColor:(int) inputColor
{
self.color = inputColor;
//Get the drawing context
CGContextRef context = UIGraphicsGetCurrentContext();
//define a gradient to use to fill the blocks
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat components[8] = { 0.0, 0.0, 0.0, 1.0, //start color
1.0, 1.0, 1.0, 1.0 }; //end color
CGFloat locations[2] = { 0.0, 1.0 };
CGGradientRef myGradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, sizeof(locations)/sizeof(CGFloat));
CGContextDrawLinearGradient(context, myGradient, CGPointMake(0, 0), CGPointMake(self.bounds.size.width, 0), 0);
}