Click here to Skip to main content
15,866,398 members
Articles / Web Development / HTML

Circular Gauge Custom Control for Silverlight 3 and WPF

Rate me:
Please Sign up or sign in to vote.
4.97/5 (71 votes)
22 Jul 2009BSD4 min read 417.7K   22.3K   157   86
An article on creating a circular gauge custom control for Silverlight 3

circulargaugecontrol/gauge_cb.png

Introduction

The Silverlight 3 SDK and toolkit includes more than a hundred controls but is missing a circular gauge control, so I decided to create one. My goal was to create a customizable gauge that is easy to use and also looks professional. You can see a live demo here.

Using the Code

In this section, I will explain how you can use the gauge control in your application. The easiest way to get started would be to copy this template code snippet in your project after referencing CircularGauge.dll and the CircularGauge namespace.

XML
<!--Black Gauge -->
<gauge:CircularGaugeControl x:Name="myGauge1" 
  Grid.Column="0" Grid.Row="0" 
  Radius="150" 
  ScaleRadius="110" 
  ScaleStartAngle="120" 
  ScaleSweepAngle="300"
  PointerLength="85" 
  PointerCapRadius="35" 
  MinValue="0" 
  MaxValue="1000" 
  MajorDivisionsCount="10" 
  MinorDivisionsCount="5" 
  CurrentValue="{Binding Score}"
  ImageSource="silverlightlogo.png"
  ImageSize="60,50"
  RangeIndicatorThickness="8"
  RangeIndicatorRadius="120"
  RangeIndicatorLightRadius="10"
  RangeIndicatorLightOffset="80"
  ScaleLabelRadius="90"
  ScaleLabelSize="40,20"
  ScaleLabelFontSize="10"
  ScaleLabelForeground="LightGray"
  MajorTickSize="10,3"
  MinorTickSize="3,1"
  MajorTickColor="LightGray"
  MinorTickColor="LightGray"
  ImageOffset="-50"
  GaugeBackgroundColor="Black"
  PointerThickness ="16"
  OptimalRangeStartValue="300"
  OptimalRangeEndValue="700" 
  DialTextOffset="40" 
  DialText="Black"
  DialTextColor="Black"> 
</gauge:CircularGaugeControl>

The CircularGauge control has several options to completely customize all its elements. Most of the property settings are intuitive to use, so I will only discuss a few here.

PropertiesComments
BackgroundSetting the background color would automatically create a gradient and glass effect using the set color as the base. This makes it very easy to drastically change the look.
ScaleRadius, ScaleLabelRadius, RangeIndicatorRadiusThese properties provide options to place the scale, range indicator, and scale labels anywhere within the gauge.
CurrentValueThe CurrentValue property is a dependency property so you can data bind to it.
ImageOffset, DialTextOffset, RangeIndicatorLightOffsetThese properties control the placement of the image, dial text, and the range indicator light along the Y-axis with respect to the center of the gauge.
OptimalRangeStartValue, OptimalRangeEndValueThese properties help define the recommended range of values. The range indicators are drawn based on these values. In addition to the range indicators, the RangeIndicatorLight also provides visual feedback using the same information. The colors representing these value zones can be customized using the BelowOptimalRangeColor, AboveOptimalRangeColor, and OptimalRangeColor values.

Creating a Custom Template

This is a look-less control, so all the details of appearance is described in the default style specified in generic.xaml. In case you would like to create a new control template, the gauge control expects the following elements in its control template:

Element NameElement Type
LayoutRootGrid
PointerPath
RangeIndicatorLightEllipse
PointerCapEllipse

You can find the complete markup for the default style in the generic.xaml file included in the source code.

Points of interest

This section outlines the main steps in creating this control. Most parts of the visual representation of the gauge control were drawn using Expression Blend. The container that contains all the elements of the gauge is a Grid. The gauge/rim, pointer cap, pointer, range indicator light, and the glass effect which is another ellipse with reduced opacity, were all drawn using Expression Blend 3. I drew the shapes and then template bound the height, width, and other attributes. Here is the markup for the pointer:

XML
 <!-- Pointer -->
<Path x:Name="Pointer" Stroke="#FFE91C1C" StrokeThickness="2" 
  Width="{TemplateBinding PointerLength}" 
  Height="{TemplateBinding PointerThickness}" HorizontalAlignment="Center"
  Data="M1,1 L1,10 L156,6 z" Stretch="Fill" RenderTransformOrigin="0,0.5" 
  RenderTransform="{Binding RelativeSource={RelativeSource TemplatedParent}, 
  Path=PointerLength, Converter={StaticResource pointerCenterConverter}}">
<Path.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF890A0A" Offset="0.197"/>
<GradientStop Color="#FFC40808" Offset="1"/>
<GradientStop Color="#FFE32323" Offset="0.61"/>
</LinearGradientBrush>
</Path.Fill>

</Path>

All the items in the template that you would like to access in code would need to be named appropriately. This is the way to establish binding between the user interface and the control. We then override the OnApplyTemplate method to get access to the named elements in the UI.

Drawing the Scale and Range Indicator

The elements which cannot be defined in the generic.xaml file are the scale and the range indicator which need to be drawn in code. The Major and Minor tick marks are just rectangles that have been rotated and moved using render transforms. Similar to the tick marks, the scale labels are text blocks that have been rotated and moved. In order to draw the scale, we need to compute the location of the points on the circumference of the scale circle. This can be computed using this formula:

circulargaugecontrol/gauge_formula4.png

Formula to find a point on the circumference, given an angle and a radius:

x = a + r * cos(θ)
y = b + r * sin(θ)

where:

  • r is the radius of the circle
  • (a,b) is the center of the circle
  • (x,y) is the point on the circumference
  • θ is the angle in degrees
  • radian = degree * π/180

Similar to drawing the scale, we use the same formula to compute the four points that comprise the range segment.

circulargaugecontrol/gauge_formula3.png

Animating the Pointer

Finally, animating the pointer only involves creating a double animation and setting its target to the pointer's rotate transform angle.

C#
void AnimatePointer(double oldcurrentvalueAngle, double newcurrentvalueAngle)
{
    if (pointer != null)
    {
        DoubleAnimation da = new DoubleAnimation();
        da.From = oldcurrentvalueAngle;
        da.To = newcurrentvalueAngle;

        double animDuration = Math.Abs(oldcurrentvalueAngle - newcurrentvalueAngle) * 
                                       animatingSpeedFactor;
        da.Duration = new Duration(TimeSpan.FromMilliseconds(animDuration));

        Storyboard sb = new Storyboard();
        sb.Completed += new EventHandler(sb_Completed);
        sb.Children.Add(da);
        Storyboard.SetTarget(da, pointer);
        Storyboard.SetTargetProperty(da, new PropertyPath(
          "(Path.RenderTransform).(TransformGroup.Children)[0].(RotateTransform.Angle)"));

        if (newcurrentvalueAngle != oldcurrentvalueAngle)
        {
            sb.Begin();
        }
    }
}

WPF Version

Porting to WPF was very easy, all I had to do was create a WPF custom control project and move the code from the Silverlight version, and everything worked without any changes.

Conclusion

This code is licensed under the Free BSD license, so feel free to use in commercial applications. I hope this gauge is useful, and would really appreciate any comments/feedback.

History

  • Version 1.0 - 07/22/2009
  • WPF version updated - 07/28/2009

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
Web Developer
United States United States
I have worked mainly with ASP.NET but also have exposure to Windows forms, WPF and Silverlight. I also enjoy developing user interfaces using Expression Blend.

Comments and Discussions

 
PraiseReally, thank you EvelynT for sharing your valuable knowledge (most importantly free of cost for commercial use also) with us. Pin
Dinesh Kudale11-Mar-22 0:11
Dinesh Kudale11-Mar-22 0:11 
QuestionDialTextFontSize Pin
Member 1400889718-Jun-21 3:16
Member 1400889718-Jun-21 3:16 
QuestionCompatible Pin
vimal26523-Dec-20 19:27
vimal26523-Dec-20 19:27 
PraiseVery nice custom control Pin
mzbas26-Aug-19 9:35
mzbas26-Aug-19 9:35 
QuestionWindows forms Pin
cescude223-Jul-18 1:13
cescude223-Jul-18 1:13 
QuestionHow to draw multiple pointers for this gauge? Pin
Member 1360677524-Jan-18 18:40
Member 1360677524-Jan-18 18:40 
QuestionChange minvalue & maxvalue for every color? Pin
Member 1120147010-Oct-17 23:26
Member 1120147010-Oct-17 23:26 
Questionthe enumerator is not valid because the collection changed ‘0’ is not a valide value for property 'fontsize' Pin
Niki_yu27-Apr-17 15:27
Niki_yu27-Apr-17 15:27 
QuestionExcellent Pin
Member 1175620110-Jun-15 9:11
Member 1175620110-Jun-15 9:11 
QuestionScaling down size of gauge Pin
Member 1141705131-Jan-15 8:02
Member 1141705131-Jan-15 8:02 
AnswerRe: Scaling down size of gauge Pin
Julien Barbier6-Feb-15 3:08
Julien Barbier6-Feb-15 3:08 
QuestionDesign Rendering Error Pin
cohay29-Jan-15 20:30
cohay29-Jan-15 20:30 
SuggestionVery good - Show start value Pin
FriedhelmEichin7-Jul-14 1:24
FriedhelmEichin7-Jul-14 1:24 
QuestionDo not see the CircularGauge.dll in either the WPF or Silverlight zip files Pin
Member 1048922610-Apr-14 11:56
Member 1048922610-Apr-14 11:56 
QuestionRemoving the outer ring Pin
Member 940689827-Jan-14 4:04
Member 940689827-Jan-14 4:04 
AnswerRe: Removing the outer ring Pin
Member 149276788-Feb-21 2:18
Member 149276788-Feb-21 2:18 
QuestionChanging "optimal" ranges Pin
cw229020-Jan-14 23:50
cw229020-Jan-14 23:50 
QuestionThank you Pin
Petr Ivankov7-Jan-14 0:12
Petr Ivankov7-Jan-14 0:12 
Questionvery good article! Pin
nettian22-Dec-13 12:40
nettian22-Dec-13 12:40 
QuestionPre-compiling show in XAML page Pin
Anton Protasov16-Sep-13 2:01
Anton Protasov16-Sep-13 2:01 
QuestionThank you Pin
hossein bakhtiari27-Mar-13 10:01
hossein bakhtiari27-Mar-13 10:01 
Questionvery nice Pin
BillW3326-Mar-13 10:59
professionalBillW3326-Mar-13 10:59 
Questionhi thanks for your sharing but i have a question Pin
mistergamer26-Nov-12 2:57
mistergamer26-Nov-12 2:57 
QuestionSetting StartValue for the Pointer Pin
Bullimann15-Jul-12 20:27
Bullimann15-Jul-12 20:27 
AnswerRe: Setting StartValue for the Pointer Pin
Member 1283622015-Dec-20 4:02
Member 1283622015-Dec-20 4:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.