# Silver Challenge

#1

I looked at a color wheel and noted how the RGB values changed based on the angle, and implemented the rules for each angle interval.

[code]- (void)drawRect:(CGRect)rect
{
for (BNRLine *line in self.finishedLines) {
float redVal, greenVal, blueVal;
float angle = atan2f(line.begin.y - line.end.y, line.end.x - line.begin.x);
//normalize atan from [-pi,pi] to [0,2pi]
if (angle < 0) {
angle += 2 * M_PI;
}
// each pi/3 interval gets different rules

``````    //0 to 30deg
if (angle > 0 && angle <= 1 * M_PI / 6.0) {
redVal = [self normalizeAngle:angle
from:-M_PI / 6.0
to:M_PI / 6.0];
greenVal = 1;
blueVal = 0;
//30 to 90deg
} else if (angle > 1 * M_PI / 6.0 && angle <= 3 * M_PI / 6.0){
redVal = 1;
greenVal = 1 - [self normalizeAngle:angle
from:1 * M_PI / 6.0
to:3 * M_PI / 6.0];
blueVal = 0;
//90 to 150deg
} else if (angle > 3 * M_PI / 6.0 && angle <= 5 * M_PI / 6.0){
redVal = 1;
greenVal = 0;
blueVal = [self normalizeAngle:angle
from:3 * M_PI / 6.0
to:5 * M_PI / 6.0];
//150 to 210deg
} else if (angle > 5 * M_PI / 6.0 && angle <= 7 * M_PI / 6.0) {
redVal = 1 - [self normalizeAngle:angle
from:5 * M_PI / 6.0
to:7 * M_PI / 6.0];
greenVal = 0;
blueVal = 1;
//210 to 270deg
} else if (angle > 7 * M_PI / 6.0 && angle <= 9 * M_PI / 6.0) {
redVal = 0;
greenVal = [self normalizeAngle:angle
from:7 * M_PI / 6.0
to:9 * M_PI / 6.0];
blueVal = 1;
//270 to 330deg
} else if (angle > 9 * M_PI / 6.0 && angle <= 11 * M_PI / 6.0){
redVal = 0;
greenVal = 1;
blueVal = 1 - [self normalizeAngle:angle
from:9 * M_PI / 6.0
to:11 * M_PI / 6.0];
//330 to 360deg
} else {
redVal = [self normalizeAngle:angle
from:11 * M_PI / 6.0
to:13 * M_PI / 6.0];
greenVal = 1;
blueVal = 0;
}
NSLog(@"angle:%f, R:%f, G:%f, B:%f", angle, redVal, greenVal, blueVal);
[[UIColor colorWithRed:redVal
green:greenVal
blue:blueVal
alpha:1] set];
[self strokeLine:line];
}
[[UIColor redColor] set];
for (BNRLine *line in [self.linesInProgress allValues]) {
[self strokeLine:line];
}
``````

}

• (float)normalizeAngle:(float)angle
from:(float)min
to:(float)max
{
if (angle > max || angle < min) {
NSLog(@“normalizeAngle out of range,”);
}

return (angle - min) / (max - min);
}
[/code]

The result:

Any ideas how I could simplify or improve the code? I feel like there is a nicer solution than what I did. Thanks.

#2

Here is the solution in the most basic possible way.
Please tell me if ive missed anything

[code]- (void)drawRect:(CGRect)rect {
for (BNRLine *line in self.finishedLines)
{
[[self colorBasedOnAngleWithLine:line]set];
[self strokeLine:line];
}
[[UIColor redColor]set];
for (NSValue *key in self.linesInProgress) {
[self strokeLine:self.linesInProgress[key]];
}
}

• (UIColor *) colorBasedOnAngleWithLine:(BNRLine *) line
{
float angleVal = atan2f(line.end.y - line.begin.y, line.end.x - line.end.y);//atan2(y2-y1,x2-x1)

``````if (angleVal > 3)
return [UIColor cyanColor];
``````

else
{
return [UIColor orangeColor];
}
return [UIColor purpleColor];
}
[/code]