Skip to content

Drawing Multiple Color Gradients

Xojo does not have a built-in way to generate gradients, but you can do this yourself with some simple code.

You can generate gradients by blending the two colors one line at a time like this:

Dim startColor As Color = &cff0000 
Dim endColor As Color = &c0000ff
Dim p as New Picture(g.Width, g.Height)
Dim samt, eamt As Double

For i As Integer = 0 To p.Height
  samt = 1 - (i / p.Height)
  eamt = i / p.Height
  p.Graphics.ForeColor = RGB((startColor.Red * samt) + (endColor.Red * eamt), _
   (startColor.Green *samt) + (endColor.Green * eamt), _
   (startColor.Blue * samt) + (endColor.Blue * eamt))
  p.Graphics.DrawLine(-1, i, p.Width+1, i)

g.DrawPicture(p, 0, 0)

The above code works to create a gradient by blending one color to another, but what if you want to create a gradient from more than two colors? The GradientExample project shows you how you can create both a linear and radial gradient from more than two colors. It uses a Pair to specify the color percent and RGB value and then creates the gradient on the fly. Play around with the example so you can see how to use gradients to make your apps look more snazzy.


This example project is included with Xojo:

Examples/Graphics and Multimedia/GradientExample

Be sure to follow us on Twitter (@xojo) for more Xojo tips and techniques.

Note: A version of this post was previously published in August 2009.