Quick Tip: Use ColorGroup in Desktop Projects

Did you know that you can already use the ColorGroup class introduced in Xojo 2019.3 (according to Xojo, initially for iOS) in desktop projects? So far, the ColorGroup Editor is missing for desktop projects, but you can create a ColorGroup in code. However, if you drag a ColorGroup from an iOS project into the desktop project, the ColorGroup Editor is also available. With the “Named” color constants, however, you cannot use all colors in desktop projects, because the list of colors supported by iOS was returned. But the dynamic colors all work fine.

Steps:

  1. Add a property of type ColorGroup (MyColor) to your window
  2. Now add the following line in the Open-Event of the window
MyColor = New ColorGroup(Color.Red, Color.Green) // Light, Dark
  1. Add to the Paint-Event window with the following code

g.DrawingColor = MyColor g.FillRectangle(10, 10, 100, 100)
4) Run your Project

Alternative:
Another possibility is to create a Computed Property of type Color and write the following code into the getter

[code]Static myColor As ColorGroup

If myColor Is Nil Then
myColor = New ColorGroup(Color.Red, Color.Green)
End If

Return myColor[/code]

Example of use:

  • Alternating row colors of a Listbox (macOS style) via Listbox.CellBackgroundPaint-Event

If row Mod 2 = 0 Then g.DrawingColor = MyColor g.FillRectangle(0, 0, g.Width, g.Height) End If

Note: Currently this apparently only works in conjunction with the Graphics object. For example, if you assign the ColorGroup to a label, the label will get the correct color at run time, but if you change the color mode of macOS at run time, the label will keep the previously set color.

Still, for self-drawn controls/graphics in a Canvas/Listbox, it works quite well.

Stupid question: what can I do with ColorGroups that I can’t do with a simple method like

if Color.IsDarkMode then Return kBarColorDM else Return kBarColor end if

?

i guess if you assign a colorgroup it choose the color self based on dark mode or light mode?

That’s what my code does, too.

The advantage is that you can create a centrally managed dynamic color only once, without code (unlike before, if you copy a ColorGroup from an iOS project to a desktop project, otherwise via code), and use it project wide.

if you replace this with your Method yes

or computed property.

but i think ColorGroup can stored in a simple property.

FWIW, ColorGroups that use named colors (such as iOS color “labelColor”) will automatically fall back to the defined default color for versions of iOS which don’t include said color.