tags:

views:

309

answers:

2

I am trying to use the MakeColor method in the GDIPAPI unit but the conversion from int to byte is not returning me the correct value.

Example

var
    argbStr: string;
    A, R, G, B: Byte;
begin
    argbStr := 'ffffcc88';
    A := StrToInt('$' + Copy(AValue, 1, 2));
    R := StrToInt('$' + Copy(AValue, 3, 2));
    G := StrToInt('$' + Copy(AValue, 5, 2));
    B := StrToInt('$' + Copy(AValue, 7, 2));
    Result := MakeColor(A, R, G, B);
end;

What am I doing wrong?

A: 

Changing the type of A, R, G, B to be Integer seemed to fix the issue. It must be something to do with the casting between Integer -> Byte.

James
+3  A: 

The color components in your string are in the same order they would have in a ARGB value. Therefore, you don't need to separate the components before combining them with MakeColor. You can do the conversion directly:

function StringToARGB(const argbStr: string): GDIPAPI.ARGB;
begin
  Result := ARGB(StrToInt('$' + argbStr));
end;

The type-cast is necessary to suppress a range-checking error you'd get whenever the alpha component was greater than 127; StrToInt returns a signed integer, but ARGB is an unsigned type.

Rob Kennedy
@Rob, even better! What about if I only had RBG? Would I just append `ff` to the string?
James
@Rob, I guess you meant to write `StrToInt`, not `IntToStr`.
François
Yes. Or, if you want to make sure that any color you might get is fully, so this: `Result := AlphaMask or ARGB(StrToInt('$' + argbStr));`
Rob Kennedy