A lap around the UWP Community Toolkit Radial Gauge control

The XAML and Composition API Radial Gauge control that I developed a while ago is now part of to the UWP Community Toolkit on GitHub. Its code was cleaned up, thanks to peer pressure from fellow MVP’s. At the same time the gauge’s functionality was extended, based on community feedback. V1.1 of the UWP Community Toolkit was just released, here is the new official Radial Gauge documentation.

The new Radial Gauge comes with a lot more configurable properties. Its default look and feel and its basic constituents did not change however:

compositiongauge_anatomy

Properties

Here’s the alphabetic list of public dependency properties. The properties that are tagged with an asterisk are brand new:

IsInteractive* bool, default false Determines whether the control accepts changing its Value through interaction.
MaxAngle* int, default 150 The stop angle of the scale, in degrees.
Maximum double, default 100 The maximum value on the scale.
MinAngle* int, default -150 The start angle of the scale, in degrees.
Minimum double, default 0 The minimum value on the scale.
NeedleBrush SolidColorBrush, default Red The color of the needle.
NeedleLength* double, default 100 The length of the needle, in percentage of the gauge radius.
NeedleWidth* double, default 5 The width of the needle, in percentage of the gauge radius.
ScaleBrush Brush, default solid DarkGray The background color of the scale.
ScaleTickBrush Brush, default solid Black The color of the ticks on the scale.
ScaleTickWidth* double, default 2.5 The scale tick width, in percentage of the gauge radius.
ScaleWidth double, default 26 The thickness of the scale in pixels, in percentage of the gauge radius.
StepSize* double, default 0 The rounding interval for the Value.
TickBrush SolidColorBrush, default White The color of the outer ticks.
TickLength* double, default 18 The outer tick length, in percentage of the gauge radius.
TickSpacing int, default 10 The spacing between ticks, in Value units.
TickWidth* double, default 5 The outer tick width, in percentage of the gauge radius.
TrailBrush Brush, default solid Orange The color of the trail following the needle. 
Unit string The unit measure to display.
UnitBrush Brush, default solid White The color of the unit measure text. 
Value double, default 0 The value to represent.
ValueBrush Brush, default solid White The color of the value text.
ValueStringFormat string, default ‘N0’ (integer values) The StringFormat to apply to the displayed value.

Each of these dependency properties has a PropertyMetadata with a default value (so you don’t have to provide one) and a PropertyChangedCallback (so any change at runtime is reflected immediately in the gauge’s looks and behavior).

There are three such callbacks:

  • OnValueChanged: called when the value changed – redraws the trail and rotates the needle
  • OnInteractivityChanged: called when IsInteractive changed (see further)
  • OnScaleChanged: called when the scale needs to be redrawn
  • OnFaceChanged: called when the needle and ticks need to be redrawn

The control is responsive: whenever a property value is changed, one (or more) of these callbacks is executed.

What’s new in Radial Gauge v1.1?

Height and Width of face elements are configurable.

In the previous versions of the Radial Gauge, the height and width of needle and ticks was fixed to give the control its ‘chubby’ Windows 8 look. To customize the gauge, you could only play with its colors:

compositiongauge_gallery

The new version allows you to go for a thinner look and feel (and more):

Gauge_Widths

Here’s part of the XAML for the first gauge from the previous screenshot. You can now specify the width of all constituents:

<controls:RadialGauge Unit="Things"
                        NeedleWidth="2"
                        TickWidth="2"
                        ScaleWidth="2" />

It’s interactive.

The previous versions of the Radial Gauge were rather passive: the control could only be used to display a Value. The new version comes with a property called ‘Isinteractive’ which make the control … interactive. Just like with a Slider control you can use touch, mouse, or pen to update the Value. And I admit: I didn’t try the XBox controller.

In interactive mode, you can place the Needle by tapping or dragging, and the control will adjust its Value. Here’s how this works: based on the value of the IsInteractive property the control registers or unregisters handlers for the Tapped and the ManipulationDelta events and it sets the corresponding ManipulationMode:

private static void OnInteractivityChanged(
	DependencyObject d, 
	DependencyPropertyChangedEventArgs e)
{
    RadialGauge radialGauge = (RadialGauge)d;

    if (radialGauge.IsInteractive)
    {
        radialGauge.Tapped += radialGauge.RadialGauge_Tapped;
        radialGauge.ManipulationDelta += 
		radialGauge.RadialGauge_ManipulationDelta;
        radialGauge.ManipulationMode = 
		ManipulationModes.TranslateX | 
		ManipulationModes.TranslateY;
    }
    else
    {
        radialGauge.Tapped -= radialGauge.RadialGauge_Tapped;
        radialGauge.ManipulationDelta -= 
		radialGauge.RadialGauge_ManipulationDelta;
        radialGauge.ManipulationMode = ManipulationModes.None;
    }
}

Both event handlers apply the same logic: the current position is translated to the corresponding needle angle, which is then translated to the gauge Value. You can not place the needle outside the scale – the triangle from MaxAngle to MinAngle) is happily ignored:

    private void RadialGauge_ManipulationDelta(
	object sender, 
	ManipulationDeltaRoutedEventArgs e)
        {
            SetGaugeValueFromPoint(e.Position);
        }

        private void RadialGauge_Tapped(
	object sender, 
	TappedRoutedEventArgs e)
        {
            SetGaugeValueFromPoint(e.GetPosition(this));
        }

        private void SetGaugeValueFromPoint(Point p)
        {
            var pt = new Point(
	p.X - (ActualWidth / 2), 
	-p.Y + (ActualHeight / 2));

            var angle = Math.Atan2(pt.X, pt.Y) * 180 / Math.PI;
            var value = Minimum + 
	((Maximum - Minimum) * (angle - MinAngle) / (MaxAngle - MinAngle));
            if (value < Minimum || value > Maximum)
            {
                // Ignore positions outside the scale angle.
                return;
            }

            Value = value;
        }

To prevent rounding issues when setting the Value through interaction, the control was extended with a StepSize dependency property. It determines the rounding interval for the Value. At the default StepSize value of zero, the control does no rounding at all. Set it to one if you only want integer values.

Each time the Value changes, the StepSize adjustment is applied:

if (radialGauge.StepSize != 0)
{
    radialGauge.Value = radialGauge.RoundToMultiple(
	radialGauge.Value, 
	radialGauge.StepSize);
}

I borrowed the rounding algorithm from the Rating Control. It’s unfortunate that there’s no such function in the System.Math class:

private double RoundToMultiple(double number, double multiple)
{
    double modulo = number % multiple;
    if ((multiple - modulo) <= modulo)
    {
        modulo = multiple - modulo;
    }
    else
    {
        modulo *= -1;
    }

    return number + modulo;
}

The begin and end angles of the scale are configurable.

In the previous iterations of the Radial Gauge, the arc of the scale was hardcoded and went clockwise from down left (-150°) to down right (150°). This gave the gauge a nice circular look – which is excellent in a responsive design context. It was also easy to find a place to display the value and unit information: centered at the bottom of the control. That 300° symmetrical look is still the default look, and here’s the corresponding style:

<Style TargetType="local:RadialGauge">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:RadialGauge">
                <Viewbox>
                    <Grid x:Name="PART_Container"
                          Height="200"
                          Width="200"
                          Background="Transparent">

                        <!-- Scale -->
                        <Path Name="PART_Scale"
                              Stroke="{TemplateBinding ScaleBrush}"
                              StrokeThickness="{TemplateBinding ScaleWidth}" />

                        <!-- Trail -->
                        <Path Name="PART_Trail"
                              Stroke="{TemplateBinding TrailBrush}"
                              StrokeThickness="{TemplateBinding ScaleWidth}" />

                        <!-- Value and Unit -->
                        <StackPanel VerticalAlignment="Bottom"
                                    HorizontalAlignment="Center">
                            <TextBlock Name="PART_ValueText"
                                       Foreground="{TemplateBinding ValueBrush}"
                                       FontSize="20"
                                       FontWeight="SemiBold"
                                       Text="{TemplateBinding Value}"
                                       TextAlignment="Center"
                                       Margin="0 0 0 2" />
                            <TextBlock Foreground="{TemplateBinding UnitBrush}"
                                       FontSize="16"
                                       TextAlignment="Center"
                                       Text="{TemplateBinding Unit}"
                                       Margin="0" />
                        </StackPanel>
                    </Grid>
                </Viewbox>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

It’s a simple style: you just have to tell the control where to draw the arcs and where to draw the value and unit texts. That’s the only XAML in the gauge, the rest (needle and ticks) is drawn by the Composition API.

The scale’s minimum and maximum angles are now Dependency Properties, so you can configure them. The proposed value ranges are -180° to 0° for MinAngle and 0° to 180° for MaxAngle.

Gauge_Angles

Feel free to deviate from the proposed values for MinAngle and MaxAngle. These were just the ranges that I had in mind when implementing all the internal calculations. Here are two examples of fully functional gauges that operate outside of the proposed ranges:

Gauge_SmallArcs

When you deviate from the default minimum or maximum angles, you probably need to retemplate the control to position the value and unit measure text. So I created a sample app that allows you to build and test your own templates. Here’s its main page with some sample templates:

Gauge1.1

My favorite template is the 270° gauge, based on RPM and speed indicators in cars. It’s three quarters of a circle (from -180° to +90°), the unit measure is neatly placed at the end of the scale, and the value appears in big in the bottom right quadrant.

Here’s how 270° gauges look like in a SquareOfsquares test container:
Template270

This is the corresponding template – it’s called it ‘Audi’ because it looks like the gauges I stare at when commuting:

    <Style x:Key="Audi"
           TargetType="controls:RadialGauge">
        <Setter Property="MinAngle"
                Value="-180" />
        <Setter Property="MaxAngle"
                Value="90" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="controls:RadialGauge">
                    <Viewbox>
                        <Grid x:Name="PART_Container"
                              Height="200"
                              Width="200"
                              Background="Transparent">
                            <Grid.RowDefinitions>
                                <RowDefinition />
                                <RowDefinition />
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition />
                                <ColumnDefinition />
                            </Grid.ColumnDefinitions>

                            <!-- Scale -->
                            <Path Name="PART_Scale"
                                  Stroke="{TemplateBinding ScaleBrush}"
                                  StrokeThickness="{TemplateBinding ScaleWidth}"
                                  Grid.ColumnSpan="2"
                                  Grid.RowSpan="2" />

                            <!-- Trail -->
                            <Path Name="PART_Trail"
                                  Stroke="{TemplateBinding TrailBrush}"
                                  StrokeThickness="{TemplateBinding ScaleWidth}"
                                  Grid.ColumnSpan="2"
                                  Grid.RowSpan="2" />

                            <!-- Value and Unit -->
                            <TextBlock Name="PART_ValueText"
                                       Foreground="{TemplateBinding ValueBrush}"
                                       FontSize="40"
                                       FontWeight="SemiBold"
                                       Text="{TemplateBinding Value}"
                                       TextAlignment="Center"
                                       VerticalAlignment="Center"
                                       Grid.Column="1"
                                       Grid.Row="1" />
                            <TextBlock Foreground="{TemplateBinding UnitBrush}"
                                       FontSize="16"
                                       FontWeight="Light"
                                       TextAlignment="Right"
                                       Text="{TemplateBinding Unit}"
                                       VerticalAlignment="Top"
                                       Margin="0 2 0 0"
                                       Grid.Column="1"
                                       Grid.Row="1" />
                        </Grid>
                    </Viewbox>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Here are some examples of other templates:

Template180

Template360

It has a NuGet package

The Radial Gauge is distributed through the Microsoft.Uwp.Toolkit.UI.Controls NuGet package:

NuGet

Make sure to install v1.1.0 or later.

As you see, the UWP Community Toolkit is a powerful and flexible control. If you want a playground to test some styles and templates, then checkout this sample app.

Enjoy!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s