Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Library: Grafik / Sound / Multimedia (https://www.delphipraxis.net/21-library-grafik-sound-multimedia/)
-   -   Delphi Farbverlauf berechnen (https://www.delphipraxis.net/56754-farbverlauf-berechnen.html)

shmia 10. Nov 2005 15:31


Farbverlauf berechnen
 
Folgende Funktionen berechnen einen Farbverlauf zwischen 2 oder mehr Farben.
Die Überblendung wird über den Parameter blend gwählt, der sich zwischen 0.0 und 1.0 bewegen darf.
Ich habe bewusst die Berechnung des Farbverlaufs vom Zeichnen des Verlaufs getrennt.
Damit kann der Farbverlauf in jede beliebige Richtung und auf beliebige grafische Objekte (Rechteck, Kreis,...) angewendet werden. (siehe Beispiel unten)

Delphi-Quellcode:
// Farbe zwischen 2 vorgegebenen Farbwerten berechnen
function ColorBetween(C1, C2 : TColor; blend:Real):TColor;
var
   r, g, b : Byte;

   y1, y2 : Byte;
begin
   C1 := ColorToRGB(C1);
   C2 := ColorToRGB(C2);

   y1 := GetRValue(C1);
   y2 := GetRValue(C2);

   r := Round(y1 + (y2-y1)*blend);

   y1 := GetGValue(C1);
   y2 := GetGValue(C2);

   g := Round(y1 + (y2-y1)*blend);

   y1 := GetBValue(C1);
   y2 := GetBValue(C2);

   b := Round(y1 + (y2-y1)*blend);
   Result := RGB(r, g, b);
end;

// Farbe zwischen beliebig vielen vorgegebenen Farbwerten berechnen
function ColorsBetween(colors:array of TColor; blend:Real):TColor;
var
   a : Integer;
   faktor : Real;
begin
   if Length(colors) < 2 then
      raise Exception.Create('ColorsBetween() at least 2 Colors required');

   if blend <= 0.0 then
      Result := colors[0]
   else if blend >= 1.0 then
      Result := colors[High(colors)]
   else
   begin
      a := Trunc(High(colors) * blend);
      faktor := 1.0 / High(colors);

      Result := ColorBetween(colors[a], colors[a+1], (blend-(a * faktor)) / faktor);
   end;
end;
Zum Testen der Funktionen setzt man einen Trackbar auf ein Formular und schreibt dann im OnChange - Event:
Delphi-Quellcode:
procedure TForm1.TrackBar2Change(Sender: TObject);
var
   blend : Real;
begin
   blend := TrackBar1.Position / TrackBar1.Max;
   Self.Color := ColorsBetween([clBlack, clRed, clGreen, clwhite], blend);
end;
ein Beispiel für ein farbiges Rechteck:
Delphi-Quellcode:
var
   radius, r : Integer;
   rt : TRect;
begin
   radius := 100;
   for r := radius downto 1 do
   begin
      rt := Rect(-r, -r, r, r);
      OffsetRect(rt, 400, 200);
      Canvas.Pen.Color := ColorsBetween([clBlack, clRed, clYellow], r / radius);
      Canvas.Polygon([Point(rt.left, rt.top), Point(rt.right, rt.top), Point(rt.right, rt.Bottom), Point(rt.left, rt.bottom)]);
   end;
end;


Alle Zeitangaben in WEZ +1. Es ist jetzt 07:59 Uhr.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz