In this tutorial, we will show you how to implement an automatic color changing for any control on the form (without using FMX animations).
Change the color randomly
- Put a “Timer” control on the form.
- Set the required duration for changing the color, in the Timer “Duration” property.
- Now, open the “OnTimer” event handler and write the code below to change the “Color” property of some controls to a random color generated by the function “MakeColor()” (from the unit “System.UIConsts”) and by using random integers (0 to 255) as values for the color’s RGB components.
Procedure TForm1.Timer1Timer(Sender: TObject);
Begin
Color := MakeColor(Random(255), Random (255), Random(255));
End;
Remarque
The function “MakeColor()” is implemented in the RTL, so it is cross platform.
If your project is on VCL (Windows-only), you can use the function “RGB()” implemented in the unit “WinAPI.Windows”.
Procedure TForm1.Timer1Timer(Sender: TObject);
Begin
Color := RGB(Random(255), Random (255), Random(255));
End;
Change the color from a list of predefined colors
First, go to the implementation section of your form’s unit, and declare a global integer variable (as color index) with the default value (-1).
...
Implementation
var
colorIndex : integer = -1;
...
Now, put a “Timer” control on the form, and set the required duration for changing the color, in the Timer “Duration” property.
Open the “OnTimer” event handler and write the code below to change the “Color” property of some controls :
- Declare an array constant containing your predefined colors, for example here, three colors : Red, Blue and Green (be aware of the difference in naming the colors constants between VCL and FMX).
- Write a condition to check if the previous global variable (the color index) is less than the index of the last item in the colors array, then increment the color index. Otherwise, set its value to zero, to restart the color sequence.
- Set the value of your control’s “Color” property to a color in the previous array with color index variable as index.
Procedure TForm1.Timer1Timer(Sender: TObject);
Const
Colors : array[0..2] of TColor = (Red, Blue, Green) ;
Begin
If colorIndex < (Length(Colors) -1) then inc(colorIndex)
else colorIndex := 0;
Color := Colors[colorIndex];
End;
Final thoughts
- You can make a simultaneous color changing for many controls, by setting their “Color” property in the same “OnTimer” event handler.
- If you want to make a different color changing for some controls, you have to put as many “Timer” controls as you need, then you set their “Duration” property and “OnTimer” event handlers separately.