11

Ребят, подскажите как сделать полукруглый прогресс бар? С обычным вообще не возникает проблем. Находил только больно уж сложные, круглые примеры введите сюда описание изображения

1

1 ответ 1

15

Просто тут и не будет, придется помудрить с геометрией.

Ну что ж, давайте создадим UserControl, я назвал его MyProgress.

Рисовать будем с помощью Path. Контрол будет состоять из двух Path - закрашенного и незакрашенного (закрашенного другим цветом). Для упрощения расчетов я взял эллипс с радиусами 100 и центром в точке (100,100).

Нам нужно нарисовать 2 луча из центра и дугу:

<Path Fill="Blue" Stroke="Black">
    <Path.Data>
        <PathGeometry>
            <PathFigure StartPoint="100,100">
                <LineSegment Point="0,100"/>
                <ArcSegment Point="170.71,29.29"
                            Size="100,100"
                            SweepDirection="Clockwise"/>
                <LineSegment Point="100,100"/>
            </PathFigure>
        </PathGeometry>
    </Path.Data>
</Path>

Точку я рассчитал для варианта 75% заполненности, вот что уже получается: 1

Теперь из этого сектора нужно вырезать круг меньшего диаметра, сделаем это с помощью CombinedGeometry в режиме Exclude:

<Path Fill="Blue" Stroke="Black">
    <Path.Data>
        <CombinedGeometry GeometryCombineMode="Exclude">
            <CombinedGeometry.Geometry1>
                <PathGeometry>
                    <PathFigure StartPoint="100,100">
                        <LineSegment Point="0,100"/>
                        <ArcSegment Point="170.71,29.29"
                                    Size="100,100"
                                    SweepDirection="Clockwise"/>
                        <LineSegment Point="100,100"/>
                    </PathFigure>
                </PathGeometry>
            </CombinedGeometry.Geometry1>
            <CombinedGeometry.Geometry2>
                <EllipseGeometry Center="100,100" RadiusX="80" RadiusY="80"/>
            </CombinedGeometry.Geometry2>
        </CombinedGeometry>
    </Path.Data>
</Path>

2

Теперь аналогично рисуем вторую часть другим цветом:

<Path Fill="Cyan" Stroke="Black">
    <Path.Data>
        <CombinedGeometry GeometryCombineMode="Exclude">
            <CombinedGeometry.Geometry1>
                <PathGeometry>
                    <PathFigure StartPoint="100,100">
                        <LineSegment Point="200,100"/>
                        <ArcSegment Point="170.71,29.29"
                                    Size="100,100"
                                    SweepDirection="Counterclockwise"/>
                        <LineSegment Point="100,100"/>
                    </PathFigure>
                </PathGeometry>
            </CombinedGeometry.Geometry1>
            <CombinedGeometry.Geometry2>
                <EllipseGeometry Center="100,100" RadiusX="80" RadiusY="80"/>
            </CombinedGeometry.Geometry2>
        </CombinedGeometry>
    </Path.Data>
</Path>

3

С разметкой пока всё, останется только привязать координаты рассчитанной точки в ArcSegment.

Займемся кодом контрола:

Свойство зависимости Value:

public static DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double),
                    typeof(MyProgress), new FrameworkPropertyMetadata(OnValueChanged));

Вспомогательное свойство зависимости с координатами точки дуги:

protected static DependencyProperty AuxiliaryPointProperty = DependencyProperty.Register("AuxiliaryPoint",
                    typeof(Point), typeof(MyProgress));

Стандартные оболочки для этих свойств:

public double Value
{
    get => (double)GetValue(ValueProperty);
    set => SetValue(ValueProperty, value);
}

protected Point AuxiliaryPoint
{
    get => (Point)GetValue(AuxiliaryPointProperty);
    set => SetValue(AuxiliaryPointProperty, value);
}

Ну и, наконец, метод, который будет пересчитывать координаты точки при смене Value:

static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var myProgress = (MyProgress)d;
    var value = (double)e.NewValue;
    var angle = Math.PI * value / 100;
    var x = 100 - 100 * Math.Cos(angle);
    var y = 100 - 100 * Math.Sin(angle);
    myProgress.AuxiliaryPoint = new Point(x, y);
}

Теперь в разметке привяжемся к рассчитанной точке:

Point="{Binding ElementName=myProgress, Path=AuxiliaryPoint}"

Это нужно сделать для обоих ArcSegment

В разметке я дал имя контролу для упрощения кода привязки:

<UserControl ...
             Name="myProgress">

Всё. Это уже минимально рабочий прогрессбар, который можно добавить в окно:

<local:MyProgress x:Name="Progress1" Value="0"/>

Выглядит так:

4

Имейте ввиду, чтобы сделать этот контрол более-менее универсальным, вам потребуется его еще доработать, например, вынести в свойства зависимости цвета дуг и фона, минимальное и максимальное значение прогрессбара, диаметр внешнего и внутреннего круга и т.д.

Привожу код контрола полностью, MyProgress.xaml:

<UserControl x:Class="WpfProgress.MyProgress"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" Name="myProgress">
    <Grid>
        <Path Fill="Blue" Stroke="Black">
            <Path.Data>
                <CombinedGeometry GeometryCombineMode="Exclude">
                    <CombinedGeometry.Geometry1>
                        <PathGeometry>
                            <PathFigure StartPoint="100,100">
                                <LineSegment Point="0,100"/>
                                <ArcSegment Point="{Binding ElementName=myProgress, Path=AuxiliaryPoint}"
                                            Size="100,100" SweepDirection="Clockwise"/>
                                <LineSegment Point="100,100"/>
                            </PathFigure>
                        </PathGeometry>
                    </CombinedGeometry.Geometry1>
                    <CombinedGeometry.Geometry2>
                        <EllipseGeometry Center="100,100" RadiusX="80" RadiusY="80"/>
                    </CombinedGeometry.Geometry2>
                </CombinedGeometry>
            </Path.Data>
        </Path>
        <Path Fill="Cyan" Stroke="Black">
            <Path.Data>
                <CombinedGeometry GeometryCombineMode="Exclude">
                    <CombinedGeometry.Geometry1>
                        <PathGeometry>
                            <PathFigure StartPoint="100,100">
                                <LineSegment Point="200,100"/>
                                <ArcSegment Point="{Binding ElementName=myProgress, Path=AuxiliaryPoint}"
                                            Size="100,100" SweepDirection="Counterclockwise"/>
                                <LineSegment Point="100,100"/>
                            </PathFigure>
                        </PathGeometry>
                    </CombinedGeometry.Geometry1>
                    <CombinedGeometry.Geometry2>
                        <EllipseGeometry Center="100,100" RadiusX="80" RadiusY="80"/>
                    </CombinedGeometry.Geometry2>
                </CombinedGeometry>
            </Path.Data>
        </Path>
    </Grid>
</UserControl>

MyProgress.xaml.cs:

using System;
using System.Windows;
using System.Windows.Controls;

namespace WpfProgress
{
    public partial class MyProgress : UserControl
    {
        public MyProgress()
        {
            InitializeComponent();
        }

        public static DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double),
                            typeof(MyProgress), new FrameworkPropertyMetadata(OnValueChanged));
        protected static DependencyProperty AuxiliaryPointProperty = DependencyProperty.Register("AuxiliaryPoint",
                            typeof(Point), typeof(MyProgress));

        static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var myProgress = (MyProgress)d;
            var value = (double)e.NewValue;
            var angle = Math.PI * value / 100;
            var x = 100 - 100 * Math.Cos(angle);
            var y = 100 - 100 * Math.Sin(angle);
            myProgress.AuxiliaryPoint = new Point(x, y);
        }

        public double Value
        {
            get => (double)GetValue(ValueProperty);
            set => SetValue(ValueProperty, value);
        }

        protected Point AuxiliaryPoint
        {
            get => (Point)GetValue(AuxiliaryPointProperty);
            set => SetValue(AuxiliaryPointProperty, value);
        }
    }
}

Раз UserControl несемантично, я сделал стиль (благодаря помощи @VladD) для ProgressBar. Потом решил добавить возможность редактирования внутреннего радиуса из разметки. Но аттачед проперти, меняющее поведение контрола, тоже несемантично, поэтому в итоге остановился на Custom Control, наследованном от ProgressBar.

Идея используется та же, что описана в решении выше, но теперь контрол доработан полностью (наверное), поэтому разметка усложнилась из-за кучи привязок, а также из-за реализованного режима Indeterminate.

Для тех, кто хочет создать такой контрол - добавьте в проект Add - New Item - Custom Control WPF, я назвал его SemicircleProgressBar, код самого контрола предельно прост - добавлено одно свойство зависимости:

public class SemicircleProgressBar : ProgressBar
{
    static SemicircleProgressBar()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(SemicircleProgressBar),
            new FrameworkPropertyMetadata(typeof(SemicircleProgressBar)));
    }

    public static DependencyProperty CuttingFactorProperty =
        DependencyProperty.Register(nameof(CuttingFactor), typeof(double),
            typeof(SemicircleProgressBar), new FrameworkPropertyMetadata(0.8));

    public double CuttingFactor
    {
        get => (double)GetValue(CuttingFactorProperty);
        set => SetValue(CuttingFactorProperty, value);
    }
}

В появившемся файле Generic.xaml в папке Themes в корне проекта разметим стиль нового контрола:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:WpfProgress"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib">

    <Style TargetType="{x:Type local:SemicircleProgressBar}">
        <Style.Resources>
            <local:ValueToAuxiliaryPointConverter x:Key="ValueToAuxiliaryPointConverter"/>
            <local:RadiusToSizeConverter x:Key="RadiusToSizeConverter"/>
            <sys:Double x:Key="OneDouble">1.0</sys:Double>
            <sys:Double x:Key="ZeroDouble">0.0</sys:Double>
            <sys:Double x:Key="QuarterDouble">0.25</sys:Double>
            <SolidColorBrush x:Key="SPB.Progress" Color="#FF06B025"/>
            <SolidColorBrush x:Key="SPB.Background" Color="#FFE6E6E6"/>
            <SolidColorBrush x:Key="SPB.Border" Color="#FFBCBCBC"/>
        </Style.Resources>
        <Setter Property="Foreground" Value="{StaticResource SPB.Progress}"/>
        <Setter Property="Background" Value="{StaticResource SPB.Background}"/>
        <Setter Property="BorderBrush" Value="{StaticResource SPB.Border}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:SemicircleProgressBar}">
                    <Grid>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Determinate"/>
                                <VisualState x:Name="Indeterminate">
                                    <Storyboard RepeatBehavior="Forever">
                                        <DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)"
                                                         Storyboard.TargetName="Animation"
                                                         From="0" To="135"
                                                         Duration="0:0:1"/>
                                        <DoubleAnimation Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)"
                                                         Storyboard.TargetName="Animation"
                                                         From="135" To="0"
                                                         Duration="0:0:1" BeginTime="0:0:1"/>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Path Stretch="Uniform" Fill="{TemplateBinding Background}"
                              Stroke="{TemplateBinding BorderBrush}"
                              StrokeThickness="{TemplateBinding BorderThickness}">
                            <Path.Data>
                                <CombinedGeometry GeometryCombineMode="Exclude">
                                    <CombinedGeometry.Geometry1>
                                        <PathGeometry>
                                            <PathFigure StartPoint="0,1">
                                                <ArcSegment Size="1,1" Point="2,1" SweepDirection="Clockwise"/>
                                            </PathFigure>
                                        </PathGeometry>
                                    </CombinedGeometry.Geometry1>
                                    <CombinedGeometry.Geometry2>
                                        <EllipseGeometry Center="1,1"
                                                         RadiusX="{Binding CuttingFactor, RelativeSource={RelativeSource TemplatedParent}}"
                                                         RadiusY="{Binding CuttingFactor, RelativeSource={RelativeSource TemplatedParent}}"/>
                                    </CombinedGeometry.Geometry2>
                                </CombinedGeometry>
                            </Path.Data>
                        </Path>
                        <Path Name="Indicator" Stretch="Uniform"
                              Fill="{TemplateBinding Foreground}"
                              Stroke="{TemplateBinding BorderBrush}"
                              StrokeThickness="{TemplateBinding BorderThickness}">
                            <Path.Data>
                                <PathGeometry>
                                    <PathFigure StartPoint="0,1">
                                        <ArcSegment Size="1,1" SweepDirection="Clockwise">
                                            <ArcSegment.Point>
                                                <MultiBinding Converter="{StaticResource ValueToAuxiliaryPointConverter}">
                                                    <Binding Path="Value" RelativeSource="{RelativeSource TemplatedParent}"/>
                                                    <Binding Path="Minimum" RelativeSource="{RelativeSource TemplatedParent}"/>
                                                    <Binding Path="Maximum" RelativeSource="{RelativeSource TemplatedParent}"/>
                                                    <Binding Source="{StaticResource OneDouble}"/>
                                                </MultiBinding>
                                            </ArcSegment.Point>
                                        </ArcSegment>
                                        <LineSegment>
                                            <LineSegment.Point>
                                                <MultiBinding Converter="{StaticResource ValueToAuxiliaryPointConverter}">
                                                    <Binding Path="Value" RelativeSource="{RelativeSource TemplatedParent}"/>
                                                    <Binding Path="Minimum" RelativeSource="{RelativeSource TemplatedParent}"/>
                                                    <Binding Path="Maximum" RelativeSource="{RelativeSource TemplatedParent}"/>
                                                    <Binding Path="CuttingFactor" RelativeSource="{RelativeSource TemplatedParent}"/>
                                                </MultiBinding>
                                            </LineSegment.Point>
                                        </LineSegment>
                                        <ArcSegment Size="{Binding Path=CuttingFactor,
                                                                   RelativeSource={RelativeSource TemplatedParent},
                                                                   Converter={StaticResource RadiusToSizeConverter}}">
                                            <ArcSegment.Point>
                                                <MultiBinding Converter="{StaticResource ValueToAuxiliaryPointConverter}">
                                                    <Binding Path="Minimum" RelativeSource="{RelativeSource TemplatedParent}"/>
                                                    <Binding Path="Minimum" RelativeSource="{RelativeSource TemplatedParent}"/>
                                                    <Binding Path="Maximum" RelativeSource="{RelativeSource TemplatedParent}"/>
                                                    <Binding Path="CuttingFactor" RelativeSource="{RelativeSource TemplatedParent}"/>
                                                </MultiBinding>
                                            </ArcSegment.Point>
                                        </ArcSegment>
                                        <LineSegment Point="0,1"/>
                                    </PathFigure>
                                    <PathFigure StartPoint="0,0">
                                        <LineSegment Point="2,1" IsStroked="False"/>
                                    </PathFigure>
                                </PathGeometry>
                            </Path.Data>
                        </Path>
                        <Path Name="Animation" Stretch="Uniform"
                              Fill="{TemplateBinding Foreground}"
                              Stroke="{TemplateBinding BorderBrush}"
                              StrokeThickness="{TemplateBinding BorderThickness}"
                              Visibility="Collapsed" RenderTransformOrigin="0.5,1">
                            <Path.Data>
                                <PathGeometry>
                                    <PathFigure StartPoint="0,1">
                                        <ArcSegment Size="1,1" SweepDirection="Clockwise">
                                            <ArcSegment.Point>
                                                <MultiBinding Converter="{StaticResource ValueToAuxiliaryPointConverter}">
                                                    <Binding Source="{StaticResource QuarterDouble}"/>
                                                    <Binding Source="{StaticResource ZeroDouble}"/>
                                                    <Binding Source="{StaticResource OneDouble}"/>
                                                    <Binding Source="{StaticResource OneDouble}"/>
                                                </MultiBinding>
                                            </ArcSegment.Point>
                                        </ArcSegment>
                                        <LineSegment>
                                            <LineSegment.Point>
                                                <MultiBinding Converter="{StaticResource ValueToAuxiliaryPointConverter}">
                                                    <Binding Source="{StaticResource QuarterDouble}"/>
                                                    <Binding Source="{StaticResource ZeroDouble}"/>
                                                    <Binding Source="{StaticResource OneDouble}"/>
                                                    <Binding Path="CuttingFactor" RelativeSource="{RelativeSource TemplatedParent}"/>
                                                </MultiBinding>
                                            </LineSegment.Point>
                                        </LineSegment>
                                        <ArcSegment Size="{Binding Path=CuttingFactor,
                                                                   RelativeSource={RelativeSource TemplatedParent},
                                                                   Converter={StaticResource RadiusToSizeConverter}}">
                                            <ArcSegment.Point>
                                                <MultiBinding Converter="{StaticResource ValueToAuxiliaryPointConverter}">
                                                    <Binding Source="{StaticResource ZeroDouble}"/>
                                                    <Binding Source="{StaticResource ZeroDouble}"/>
                                                    <Binding Source="{StaticResource OneDouble}"/>
                                                    <Binding Path="CuttingFactor" RelativeSource="{RelativeSource TemplatedParent}"/>
                                                </MultiBinding>
                                            </ArcSegment.Point>
                                        </ArcSegment>
                                        <LineSegment Point="0,1"/>
                                    </PathFigure>
                                    <PathFigure StartPoint="0,0">
                                        <LineSegment Point="2,1" IsStroked="False"/>
                                    </PathFigure>
                                </PathGeometry>
                            </Path.Data>
                            <Path.RenderTransform>
                                <RotateTransform/>
                            </Path.RenderTransform>
                        </Path>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsIndeterminate" Value="true">
                            <Setter Property="Visibility" TargetName="Indicator" Value="Collapsed"/>
                            <Setter Property="Visibility" TargetName="Animation" Value="Visible"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Конвертеры.
ValueToAuxiliaryPointConverter:

class ValueToAuxiliaryPointConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values.Contains(DependencyProperty.UnsetValue))
            return DependencyProperty.UnsetValue;
        var v = (double)values[0];
        var min = (double)values[1];
        var max = (double)values[2];
        var r = (double)values[3];
        var ratio = (v - min) / (max - min);
        var angle = Math.PI * ratio;
        var x = 1 - r * Math.Cos(angle);
        var y = 1 - r * Math.Sin(angle);
        return new Point(x, y);
    }

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

RadiusToSizeConverter:

class RadiusToSizeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var r = (double)value;
        return new Size(r, r);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Код для демонстрации:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>

    <ProgressBar Name="ProgressBar1" Grid.Row="0" Grid.Column="0"
                 Value="75" Minimum="0" Maximum="100"
                 VerticalAlignment="Center" HorizontalAlignment="Center"
                 Height="100" Width="200"/>

    <ProgressBar Name="ProgressBar2" Grid.Row="1" Grid.Column="0"
                 IsIndeterminate="True"
                 VerticalAlignment="Center" HorizontalAlignment="Center"
                 Height="100" Width="200"/>

    <local:SemicircleProgressBar x:Name="SemiCpb1" Grid.Row="0" Grid.Column="1"
                                 Value="75" Minimum="0" Maximum="100"
                                 CuttingFactor="0.8"
                                 VerticalAlignment="Center" HorizontalAlignment="Center"
                                 Height="100" Width="200"/>

    <local:SemicircleProgressBar x:Name="SemiCpb2" Grid.Row="1" Grid.Column="1"
                                 IsIndeterminate="True"
                                 CuttingFactor="0.8"
                                 VerticalAlignment="Center" HorizontalAlignment="Center"
                                 Height="100" Width="200"/>
</Grid>

Demo

Использована информация из этого ответа

13
  • Ошибки Все так же сделал =\ 3 авг 2017 в 13:54
  • У вас студия древняя, неплохо бы обновить. А пока замените get => ... на get { return ... } и set => ... на set { ... } 3 авг 2017 в 14:15
  • 1
    Юзерконтрол немного несемантично, лучше оформить как стиль для ProgressBar'а.
    – VladD
    4 авг 2017 в 0:22
  • 1
    @ИгорьАга, зачем вам это понадобилось? Лучше уж добавить контрол в разметку и из кода управлять его видимостью 4 авг 2017 в 5:08
  • 1
    @mrid, welcome! I am glad if it was useful for you. 22 янв 2019 в 4:37

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.