WPF 径向进度条/仪表盘(例如电池仪表盘)

23
我正在为Windows 8.1和Windows Phone 8.1开发一个统一的健身应用程序。核心视图之一最好能够显示每日进度表。问题在于,我还没有想出实际的表或计量器。我希望拥有的只是一个类似于Windows Phone商店中普通电池应用中的径向进度条或类似电池表的东西。据我所知,WPF / VS 2013没有提供此类组件。我知道Telerik和其他几个第三方公司提供了类似的东西,但我更愿意使用开源组件或自己构建。有人知道新的适用于.NET 4.5和WPF的开源组件,或者有关于如何构建自己组件的示例吗?到目前为止,我找到的与此类似:链接:WPF的计量器,但我希望使用类似于这个的东西:enter image description here
1个回答

65

你可以自己构建这样的东西。首先,你需要一台 Arc 设备:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Shapes;
using System.Windows.Media;
using System.Windows;

...

public class Arc : Shape
{
    public double StartAngle
    {
        get { return (double)GetValue(StartAngleProperty); }
        set { SetValue(StartAngleProperty, value); }
    }

    // Using a DependencyProperty as the backing store for StartAngle.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty StartAngleProperty =
        DependencyProperty.Register("StartAngle", typeof(double), typeof(Arc), new UIPropertyMetadata(0.0, new PropertyChangedCallback(UpdateArc)));

    public double EndAngle
    {
        get { return (double)GetValue(EndAngleProperty); }
        set { SetValue(EndAngleProperty, value); }
    }

    // Using a DependencyProperty as the backing store for EndAngle.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty EndAngleProperty =
        DependencyProperty.Register("EndAngle", typeof(double), typeof(Arc), new UIPropertyMetadata(90.0, new PropertyChangedCallback(UpdateArc)));

    //This controls whether or not the progress bar goes clockwise or counterclockwise
    public SweepDirection Direction
    {
        get { return (SweepDirection) GetValue(DirectionProperty); }
        set { SetValue(DirectionProperty, value);}
    }

    public static readonly DependencyProperty DirectionProperty =
        DependencyProperty.Register("Direction", typeof (SweepDirection), typeof (Arc),
            new UIPropertyMetadata(SweepDirection.Clockwise));

    //rotate the start/endpoint of the arc a certain number of degree in the direction
    //ie. if you wanted it to be at 12:00 that would be 270 Clockwise or 90 counterclockwise
    public double OriginRotationDegrees
    {
        get { return (double) GetValue(OriginRotationDegreesProperty); }
        set { SetValue(OriginRotationDegreesProperty, value);}
    }

    public static readonly DependencyProperty OriginRotationDegreesProperty =
        DependencyProperty.Register("OriginRotationDegrees", typeof (double), typeof (Arc),
            new UIPropertyMetadata(270.0, new PropertyChangedCallback(UpdateArc)));

    protected static void UpdateArc(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Arc arc = d as Arc;
        arc.InvalidateVisual();
    }

    protected override Geometry DefiningGeometry
    {
        get { return GetArcGeometry(); }
    }

    protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
    {
        drawingContext.DrawGeometry(null, new Pen(Stroke, StrokeThickness), GetArcGeometry());
    }

    private Geometry GetArcGeometry()
    {
        Point startPoint = PointAtAngle(Math.Min(StartAngle, EndAngle), Direction);
        Point endPoint = PointAtAngle(Math.Max(StartAngle, EndAngle), Direction);

        Size arcSize = new Size(Math.Max(0, (RenderSize.Width - StrokeThickness) / 2),
            Math.Max(0, (RenderSize.Height - StrokeThickness) / 2));
        bool isLargeArc = Math.Abs(EndAngle - StartAngle) > 180;

        StreamGeometry geom = new StreamGeometry();
        using (StreamGeometryContext context = geom.Open())
        {
            context.BeginFigure(startPoint, false, false);
            context.ArcTo(endPoint, arcSize, 0, isLargeArc, Direction, true, false);
        }
        geom.Transform = new TranslateTransform(StrokeThickness / 2, StrokeThickness / 2);
        return geom;
    }

    private Point PointAtAngle(double angle, SweepDirection sweep)
    {
        double translatedAngle = angle + OriginRotationDegrees;
        double radAngle = translatedAngle * (Math.PI / 180);
        double xr = (RenderSize.Width - StrokeThickness) / 2;
        double yr = (RenderSize.Height - StrokeThickness) / 2;

        double x = xr + xr * Math.Cos(radAngle);
        double y = yr * Math.Sin(radAngle);

        if (sweep == SweepDirection.Counterclockwise)
        {
            y = yr - y;
        }
        else
        {
            y = yr + y;
        }

        return new Point(x, y);
    }
}

此弧拥有起始角度和结束角度。要从进度条的进度转换为这些角度,您需要一个转换器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

...

public class ProgressToAngleConverter : System.Windows.Data.IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        double progress = (double)values[0];
        System.Windows.Controls.ProgressBar bar = values[1] as System.Windows.Controls.ProgressBar;

        return 359.999 * (progress / (bar.Maximum - bar.Minimum));
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

好的,很好。那就是你所需要的一切。现在您可以编写 XAML 代码,例如:

<Window x:Class="WPFTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WPFTest"
        Title="MainWindow" Height="525" Width="525">
    <Window.Resources>
        <local:ProgressToAngleConverter x:Key="ProgressConverter"/>
        <Style TargetType="{x:Type ProgressBar}" x:Key="ProgressBarStyle">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ProgressBar}">
                        <Grid>
                            <Ellipse Stroke="Black" Fill="{TemplateBinding Background}"/>
                            <Ellipse Stroke="Black" Margin="40" Fill="White"/>
                            <local:Arc StrokeThickness="30" Stroke="{TemplateBinding BorderBrush}" Margin="5">
                                <local:Arc.StartAngle>
                                    <MultiBinding Converter="{StaticResource ProgressConverter}">
                                        <Binding Path="Minimum" RelativeSource="{RelativeSource TemplatedParent}"/>
                                        <Binding Path="." RelativeSource="{RelativeSource TemplatedParent}"/>
                                    </MultiBinding>
                                </local:Arc.StartAngle>
                                <local:Arc.EndAngle>
                                    <MultiBinding Converter="{StaticResource ProgressConverter}">
                                        <Binding Path="Value" RelativeSource="{RelativeSource TemplatedParent}"/>
                                        <Binding Path="." RelativeSource="{RelativeSource TemplatedParent}"/>
                                    </MultiBinding>
                                </local:Arc.EndAngle>
                            </local:Arc>
                            <TextBlock Text="{Binding Value, RelativeSource={RelativeSource TemplatedParent}, StringFormat=\{0:0\}}"
                                       Foreground="{TemplateBinding Background}" VerticalAlignment="Center" HorizontalAlignment="Center"
                                       FontSize="72" FontWeight="Bold"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <Viewbox>
            <ProgressBar Style="{StaticResource ProgressBarStyle}" Width="300" Height="300" 
                         Value="{Binding ElementName=sliderValue, Path=Value}"/>
        </Viewbox>
        <Slider Grid.Row="1" Name="sliderValue" Maximum="100" Value="50" />
    </Grid>
</Window>

现在,只需取出ProgressBarStyle,进行修改并将其应用于您喜欢的任何进度条。

最后,您将得到类似于这样的东西。玩得开心!

编辑: 您需要以下引用(我建议您创建新的空白WPF项目):

  • WindowsBase
  • PresentationCore
  • PresentationFramework

编辑:为了控制旋转方向以及进度开始的位置,我添加了两个依赖属性:Direction和OriginRotationDegrees

enter image description here


谢谢您详细的回答!大部分我都觉得很容易理解和有帮助。不幸的是,我在实现解决方案时遇到了困难。我无法“解析”或找到StreamGeometry、Pen、Point、UIPropertyMetadata和Media.DrawingContext的命名空间。当尝试使用导入时,系统中未找到DrawingContext,可能是因为未找到System.Windows.Media。我找到的建议是引用PresentationCore.dll,但这对我没有解决问题。有什么建议吗? - TheMoonbeam
我已经添加了必要的命名空间。 - Florian
1
正是我所设想的,非常感谢! - Alex Hopkins
干得好!实现起来并不难,通过调整样式可以轻松自定义。 - Mike Fuchs
我们如何将边缘变成圆角? - dnxit
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接