Title: Make a slider with a value bar in C#
The example Make a slider with a needle in C# shows how to use a PictureBox to make a simple slider. This example is similar except it draws the slider in a different style. See the previous example for information about how to make the basic slider.
The following code shows the only difference between this example and the previous one: the way it draws.
// Draw the needle.
private void picSlider_Paint(object sender, PaintEventArgs e)
{
// Calculate the needle's X coordinate.
float x = ValueToX(SliderValue);
int y = (int)(picSlider.ClientSize.Height * 0.25);
int hgt = picSlider.ClientSize.Height - 2 * y;
// Draw it.
e.Graphics.FillRectangle(Brushes.Blue,
0, y, x, hgt);
using (Pen pen = new Pen(Color.Blue, 3))
{
e.Graphics.DrawLine(pen,
x, 0,
x, picSlider.ClientSize.Height);
}
}
This code draws a thin bar horizontally inside the PictureBox. It then draws a vertical line at the selected value.
You can modify the Paint event handler in other ways to produce different effects. For example, you could draw the area to the left of the value in a solid color, fill it with a gradient brush, or tile the area with a picture.
Download the example to experiment with it and to see additional details.
|