HSV 2 DWORD by Nicholas Thompson23rd Dec 2006 12:01
|
---|
Summary Function to convert HSV values to a DWORD (as produced by the RGB function) Description Sometimes you want to control the COLOUR of a colour without changing the saturation or the value/brightness. This is next to impossible to do with pure RGB values, but it is often quite a useful thing to do (for example creating random but equally visible colours for a game). DBP doesn't handle HSV internally (AFAIK) so here is a function with remarks to do just that. Provide a Hue in the range of 0.0 to 360.0 and a Saturation and Brightness in the range of 0.0 to 1.0 and it will return a DWORD of that colour. For more information on HSV, see: Code ` This code was downloaded from The Game Creators ` It is reproduced here with full permission ` http://www.thegamecreators.com sync off h as float : s as float : v as float do cls h = rnd(360) : s = rnd(1000) * 0.001 : v = rnd(1000) * 0.001 ink hsv2dword(h, s , v), 0 print "H = " + str$(h) print "S = " + str$(s) print "V = " + str$(v) box 0, 50, 50, 100 wait key loop end remstart h: 0.0 => 360.0 s: 0.0 => 1.0 v: 0.0 => 1.0 returns: Color as DWORD remend function hsv2dword(H as float, S as float, V as float) `Sanitize the input... if H < 0.0 then H = 0.0 else if H > 360.0 then H = 360.0 if S < 0.0 then S = 0.0 else if S > 1.0 then S = 1.0 if V < 0.0 then V = 0.0 else if V > 1.0 then V = 1.0 `Variable for returned Colour returnCol as DWORD `Section of the Hue Hi as integer : Hi = (H / 60.0) mod 6 `f is a fraction of the section f as float : f = (H / 60.0) - Hi `p, q and t are temp variables used to work out the rgb values before we know where to put them p as float : p = V * (1.0 - S) q as float : q = V * (1.0 - (f * S)) t as float : t = V * (1.0 - ((1.0 - f) * S)) `Depending on the section worked out above, we store the rgb value appropriately... R as float : G as float : B as float select Hi case 0 : R = V : G = t : B = p : endcase case 1 : R = q : G = V : B = p : endcase case 2 : R = p : G = V : B = t : endcase case 3 : R = p : G = q : B = V : endcase case 4 : R = t : G = p : B = V : endcase case 5 : R = V : G = p : B = q : endcase endselect `Sanitize the output - just incase of floating point errors... if R < 0.0 then R = 0.0 else if R > 1.0 then R = 1.0 if G < 0.0 then G = 0.0 else if G > 1.0 then G = 1.0 if B < 0.0 then B = 0.0 else if B > 1.0 then B = 1.0 `Convert to Bytes and then convert to a DWORD using the rgb() function rByte as byte : rByte = R * 255 gByte as byte : gByte = G * 255 bByte as byte : bByte = B * 255 returnCol = rgb(rByte, gByte, bByte) endfunction returnCol |