Search code examples
delphidelphi-11-alexandria

What's the easiest way to create a TAlphaColor from RGB values?


What's the easiest way to create a TAlphaColor from individual R,G,B integer values?

I know of two ways. In the following, assume r,g,b are integers 0->255:

rec : TAlphaColorRec
color : TAlphaColor;

rec.A := 255;
rec.R := r;
rec.B := b;
rec.G := g;
color := rec.Color;
color := TAlphaColorF.Create(r/255, g/255, b/255).ToAlphaColor;

The former seems verbose, and the later overkill. I thought there might have been a function such as the following, but there doesn't appear to be:

color = TAlphaColor.RGBToColor (r,g,b,1)

Are there any other ways to create TAlphaColor from R,G,B values?


Solution

  • What you have is basically it. However, you don't need a separate TAlphaColorRec variable, you can type-cast the TAlphaColor variable to access its components, eg:

    var color : TAlphaColor;
    TAlphaColorRec(color).A := 255;
    TAlphaColorRec(color).R := r;
    TAlphaColorRec(color).B := b;
    TAlphaColorRec(color).G := g;
    

    This is exactly what TAlphaColorF.ToAlphaColor does internally for its Result:

    function TAlphaColorF.ToAlphaColor: TAlphaColor;
    begin
      TAlphaColorRec(Result).R := Round(R * 255);
      TAlphaColorRec(Result).G := Round(G * 255);
      TAlphaColorRec(Result).B := Round(B * 255);
      TAlphaColorRec(Result).A := Round(A * 255);
    end;