Skip to content

Commit

Permalink
Constrain CPColor components to [0.0, 1.0].
Browse files Browse the repository at this point in the history
  • Loading branch information
aljungberg committed Mar 10, 2012
1 parent 9acbe0f commit 2a031e8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
2 changes: 1 addition & 1 deletion AppKit/CPColor.j
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ function CPColorWithImages()
*/
+ (CPColor)colorWithRed:(float)red green:(float)green blue:(float)blue alpha:(float)alpha
{
return [[CPColor alloc] _initWithRGBA:[red, green, blue, alpha]];
return [[CPColor alloc] _initWithRGBA:[MAX(0.0, MIN(1.0, red)), MAX(0.0, MIN(1.0, green)), MAX(0.0, MIN(1.0, blue)), MAX(0.0, MIN(1.0, alpha))]];
}

/*!
Expand Down
18 changes: 17 additions & 1 deletion Tests/AppKit/CPColorTest.j
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
// Based on https://gist.github.com/e06f749362cb1166439f by spakanati.
var color1 = [CPColor colorWithCSSString:"rgba(127,127,127,1.0)"],
color2 = [CPColor colorWithCSSString:"rgba(127, 127, 127, 1.0)"],
color3 = [CPColor colorWithRed:127.0/255.0 green:127.0/255.0 blue:127.0/255.0 alpha:1.0],
color3 = [CPColor colorWithRed:127.0 / 255.0 green:127.0 / 255.0 blue:127.0 / 255.0 alpha:1.0],
color4 = [CPColor blackColor];

[self assertTrue:[color1 isEqual:color2] message:"[color1 isEqual:color2]"];
Expand All @@ -51,4 +51,20 @@
[self assertFalse:[color4 isEqual:color5] message:"![color4 isEqual:color5]"];
}

- (void)testOutOfRange
{
var color1 = [CPColor colorWithCalibratedRed:-1.0 green:-1.0 blue:-1.0 alpha:-.05],
color2 = [CPColor colorWithCalibratedRed:1.1 green:1.2 blue:1.3 alpha:1.05];

[self assert:0.0 equals:[color1 redComponent] message:"color1 redComponent"];
[self assert:0.0 equals:[color1 greenComponent] message:"color1 greenComponent"];
[self assert:0.0 equals:[color1 blueComponent] message:"color1 blueComponent"];
[self assert:0.0 equals:[color1 alphaComponent] message:"color1 alphaComponent"];

[self assert:1.0 equals:[color2 redComponent] message:"color2 redComponent"];
[self assert:1.0 equals:[color2 greenComponent] message:"color2 greenComponent"];
[self assert:1.0 equals:[color2 blueComponent] message:"color2 blueComponent"];
[self assert:1.0 equals:[color2 alphaComponent] message:"color2 alphaComponent"];
}

@end

0 comments on commit 2a031e8

Please sign in to comment.