Reputation: 24558
I am trying to increase darkness of RGB using pure math without relying on any framework ..
So, here is my implementation:
Provided with R, G, B ( each from 0 to 256 ) & darknessFactor ( 0 to 1 )
// this is a pseudocode
r*= darknessFactor;
g*= darknessFactor;
b*= darknessFactor;
r= int (r);
g= int (g);
b= int (b);
g <<= 8;
r <<= 16;
final_color= b + g + r ;
Then, when I tried to use it against R= 00, G= 256, B= 0, darknessFactor= 0.1, I get a result near to dark red!
Any idea?
EDIT
Would ColorTransform of actionScript 3 solve this problem?
Upvotes: 1
Views: 1140
Reputation: 123
For an RGB(R1,G1,B1), the new RGB(R2,G2,B2) darkened by the percentage/factor of p% should be:
R2 = R1 - (R1/100)*P
G2 = G1 - (G1/100)*P
B2 = B1 - (B1/100)*P
This is only the solution to your specific problem. If you want to work on something more advanced then please have a look at HSL color space and how to work with its L factor.
Upvotes: 0
Reputation: 1209
ColorTransform would be the simplest way to solve this problem without writing any new code.
See here.
The multiplier properties would be what you want in order to darken the current colour.
var colorInfo:ColorTransform = myDisplayObject.transform.colorTransform;
// Make some color transformations here.
// Reduce colour by 10%
colorInfo.redMultiplier = 0.9;
colorInfo.greenMultiplier = 0.9;
colorInfo.blueMultiplier = 0.9;
// Commit the change.
myDisplayObject.transform.colorTransform = colorInfo;
Upvotes: 0
Reputation: 15623
In principle, your pseudo-code looks good, so there must be a problem in your actual code. Although it is really strange that you would have a red result with a green input. With your code, that would be possible for a factor bigger than one, because you're not clamping the channels, so the green channel could overflow into the red one.
This will work:
function clamp(channel:Float) {
var v = Std.int(channel);
return
if (v < 0) 0;
else if (v > 0xFF) 0xFF;
else v;
}
function darken(color:Int, factor:Float) {
var r = (color >> 16) & 0xFF;
var g = (color >> 8) & 0xFF;
var b = color & 0xFF;
return
(clamp(r * factor) << 16)
+ (clamp(g * factor) << 8)
+ clamp(b * factor);
}
You can test it here: http://try.haxe.org/#b328e
Upvotes: 1
Reputation: 1624
you should use HSV intead of RGB.
first, RGB convert to HSV.
second, decrease v(brightness[0 to 1]).
finally, HSV convert to RGB.
you can easily implement converting program. or, can find library.
Upvotes: 1