Recommended Posts

the function below calculates the relative brightness of a colour (specified in hex : #008080 = 'teal')

```    //funtion to find the relative brightness of a colour (hex-code)
function Brightness(colour: string): integer;
begin
asm
function coloro(color) {
if(color.length==7){color=color.substring(1);}
var R =	parseInt(color.substring(0,2),16);
var G =	parseInt(color.substring(2,4),16);
var B =	parseInt(color.substring(4,6),16);
return Math.sqrt(R * R * .241 + G * G * .691 + B * B * .068);
}
@result = coloro(colour);
end;
end;```

and is used to determine the best text colour on specific backgrounds (brightness < 130 = white else black);

Not unlike the ColorListBox project in featured demo's. The above algorithm is a bit different than that demo and supposedly more accurate.

Function works well but I don't like the asm block. Does anyone know if there is a Delphi/Pascal routine available somewhere which does the same as the javascript parseInt function ?

Share on other sites
```function Brightness(colour: Variant): Float;
function coloro(color: Variant): Float;
var
R, G, B: Integer;
function parseInt(s: Variant{String}; radix: integer = 0): integer; external "parseInt";
begin
if(color.length=7) then color:= color.substring(1);
R :=	parseInt(color.substring(0,2), 16);
G :=	parseInt(color.substring(2,4), 16);
B :=	parseInt(color.substring(4,6), 16);
Result := sqrt(R * R * 0.241 + G * G * 0.691 + B * B * 0.068);
end;
begin
Result := coloro(colour);
end;```

Share on other sites

amazing, thanks heaps

Share on other sites

I was about to write that the snippet simply copies 2 by 2 hex characters and then converts that to an integer number.
In pure pascal it would be a bit messy since pascal's StrToInt doesnt support hex (unless prefixed by \$).
ASM sections are very much needed, they might not be pretty (not too fond on them myself) but there are some fundamental code sections that would never work if we used pascal only. Speed is also a factor to keep in mind, especially for procedures that you will call many times.

But you seem all set so i'll leave you to it! Happy coding!

Create an account

Register a new account