WPF使用DrawingContext实现绘制刻度条

作者:驚鏵 时间:2023-06-19 08:35:17 

WPF 使用 DrawingContext 绘制刻度条

  • 框架使用大于等于.NET40

  • Visual Studio 2022;

  • 项目使用 MIT 开源许可协议;

  • 定义Interval步长、SpanInterval间隔步长、MiddleMask中间步长。

  • 当步长/ 间隔步长= 需要绘制的小刻度。

  • 循环绘制小刻度,判断当前j并取中间步长的模,如果模!=零就绘制中高线。

  • StartValue 开始绘制刻度到EndValue 结束刻度。

  • CurrentGeometry 重新绘制当前刻度的Path值。

  • CurrentValue 当前值如果发生变化时则去重新CurrentGeometry 。

1) 准备Ruler.cs如下:

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

namespace WPFDevelopers.Controls
{
    public class Ruler : Control
    {
        public static readonly DependencyProperty IntervalProperty =
            DependencyProperty.Register("Interval", typeof(double), typeof(Ruler), new UIPropertyMetadata(30.0));

        public static readonly DependencyProperty SpanIntervalProperty =
            DependencyProperty.Register("SpanInterval", typeof(double), typeof(Ruler), new UIPropertyMetadata(5.0));

        public static readonly DependencyProperty MiddleMaskProperty =
            DependencyProperty.Register("MiddleMask", typeof(int), typeof(Ruler), new UIPropertyMetadata(2));

        public static readonly DependencyProperty CurrentValueProperty =
            DependencyProperty.Register("CurrentValue", typeof(double), typeof(Ruler),
                new UIPropertyMetadata(OnCurrentValueChanged));

        public static readonly DependencyProperty StartValueProperty =
            DependencyProperty.Register("StartValue", typeof(double), typeof(Ruler), new UIPropertyMetadata(120.0));

        public static readonly DependencyProperty EndValueProperty =
            DependencyProperty.Register("EndValue", typeof(double), typeof(Ruler), new UIPropertyMetadata(240.0));

        public static readonly DependencyProperty CurrentGeometryProperty =
            DependencyProperty.Register("CurrentGeometry", typeof(Geometry), typeof(Ruler),
                new PropertyMetadata(Geometry.Parse("M 257,0 257,25 264,49 250,49 257,25")));

        static Ruler()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(Ruler), new FrameworkPropertyMetadata(typeof(Ruler)));
        }

        public Ruler()
        {
            Loaded += Ruler_Loaded;
        }

        public double Interval
        {
            get => (double)GetValue(IntervalProperty);

            set => SetValue(IntervalProperty, value);
        }

        public double SpanInterval
        {
            get => (double)GetValue(SpanIntervalProperty);

            set => SetValue(SpanIntervalProperty, value);
        }

        public int MiddleMask
        {
            get => (int)GetValue(MiddleMaskProperty);

            set => SetValue(MiddleMaskProperty, value);
        }

        public double CurrentValue
        {
            get => (double)GetValue(CurrentValueProperty);

            set
            {
                SetValue(CurrentValueProperty, value);
                PaintPath();
            }
        }

        public double StartValue
        {
            get => (double)GetValue(StartValueProperty);

            set => SetValue(StartValueProperty, value);
        }

        public double EndValue
        {
            get => (double)GetValue(EndValueProperty);

            set => SetValue(EndValueProperty, value);
        }

        public Geometry CurrentGeometry
        {
            get => (Geometry)GetValue(CurrentGeometryProperty);

            set => SetValue(CurrentGeometryProperty, value);
        }

        private static void OnCurrentValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var ruler = d as Ruler;
            ruler.CurrentValue = Convert.ToDouble(e.NewValue);
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            RenderOptions.SetEdgeMode(this, EdgeMode.Aliased);
            var nextLineValue = 0d;
            var one_Width = ActualWidth / ((EndValue - StartValue) / Interval);

            for (var i = 0; i <= (EndValue - StartValue) / Interval; i++)
            {
                var numberText = DrawingContextHelper.GetFormattedText((StartValue + i * Interval).ToString(),
                    (Brush)DrawingContextHelper.BrushConverter.ConvertFromString("#FFFFFF"), FlowDirection.LeftToRight,
                    10);
                drawingContext.DrawText(numberText, new Point(i * one_Width - 8, 0));
                drawingContext.DrawLine(new Pen(new SolidColorBrush(Colors.White), 1), new Point(i * one_Width, 25),
                    new Point(i * one_Width, ActualHeight - 2));
                var cnt = Interval / SpanInterval;
                for (var j = 1; j <= cnt; j++)
                    if (j % MiddleMask == 0)
                        drawingContext.DrawLine(new Pen(new SolidColorBrush(Colors.White), 1),
                            new Point(j * (one_Width / cnt) + nextLineValue, ActualHeight - 2),
                            new Point(j * (one_Width / cnt) + nextLineValue, ActualHeight - 10));
                    else
                        drawingContext.DrawLine(new Pen(new SolidColorBrush(Colors.White), 1),
                            new Point(j * (one_Width / cnt) + nextLineValue, ActualHeight - 2),
                            new Point(j * (one_Width / cnt) + nextLineValue, ActualHeight - 5));

                nextLineValue = i * one_Width;
            }
        }

        private void Ruler_Loaded(object sender, RoutedEventArgs e)
        {
            PaintPath();
        }

        private void PaintPath()
        {
            var d_Value = CurrentValue - StartValue;
            var one_Value = ActualWidth / (EndValue - StartValue);
            var x_Point = one_Value * d_Value + ((double)Parent.GetValue(ActualWidthProperty) - ActualWidth) / 2d;
            CurrentGeometry =
                Geometry.Parse($"M {x_Point},0 {x_Point},25 {x_Point + 7},49 {x_Point - 7},49 {x_Point},25");
        }
    }
}

2) 使用RulerControlExample.xaml.cs如下:

<UserControl x:Class="WPFDevelopers.Samples.ExampleViews.RulerControlExample"
             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" 
             xmlns:local="clr-namespace:WPFDevelopers.Samples.ExampleViews"
             xmlns:wpfdev="https://github.com/WPFDevelopersOrg/WPFDevelopers"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Slider x:Name="PART_Slider" IsSnapToTickEnabled="True"
                Value="40"
                Minimum="10"
                Maximum="210"/>
        <UniformGrid Rows="3">
            <Grid Background="{StaticResource CircularDualSolidColorBrush}" Height="51" Margin="40,0">
                <Path Stroke="{StaticResource SuccessPressedSolidColorBrush}" StrokeThickness="1" Fill="{StaticResource SuccessPressedSolidColorBrush}"
                  Data="{Binding ElementName=PART_Ruler, Path=CurrentGeometry,Mode=TwoWay}" />
                <wpfdev:Ruler x:Name="PART_Ruler" Margin="40,0" Interval="20" StartValue="10" EndValue="210"
                          CurrentValue="{Binding ElementName=PART_Slider,Path=Value,Mode=TwoWay}"/>
            </Grid>
            <Grid Background="{StaticResource DangerPressedSolidColorBrush}" Height="51" Margin="40,0">
                <Path Stroke="{StaticResource SuccessPressedSolidColorBrush}" StrokeThickness="1" Fill="{StaticResource SuccessPressedSolidColorBrush}"
                  Data="{Binding ElementName=PART_Ruler1, Path=CurrentGeometry,Mode=TwoWay}" />
                <wpfdev:Ruler x:Name="PART_Ruler1" Margin="40,0" Interval="20" StartValue="10" EndValue="210"
                          CurrentValue="{Binding ElementName=PART_Slider,Path=Value,Mode=TwoWay}"/>
            </Grid>
            <Grid Background="{StaticResource WarningPressedSolidColorBrush}" Height="51" Margin="40,0">
                <Path Stroke="{StaticResource SuccessPressedSolidColorBrush}" StrokeThickness="1" Fill="{StaticResource SuccessPressedSolidColorBrush}"
                  Data="{Binding ElementName=PART_Ruler2, Path=CurrentGeometry,Mode=TwoWay}" />
                <wpfdev:Ruler x:Name="PART_Ruler2" Margin="40,0" Interval="20" StartValue="10" EndValue="210"
                          CurrentValue="{Binding ElementName=PART_Slider,Path=Value,Mode=TwoWay}"/>
            </Grid>
        </UniformGrid>
        
        
    </Grid>
</UserControl>

WPF使用DrawingContext实现绘制刻度条

来源:https://mp.weixin.qq.com/s/MUHo6TIlDl1xYM_ERa4MNQ

标签:WPF,DrawingContext,刻度条
0
投稿

猜你喜欢

  • 详解Android v1、v2、v3签名(小结)

    2022-07-01 16:56:44
  • SpringBoot+WebSocket实现多人在线聊天案例实例

    2022-08-22 11:53:08
  • Java spring的三种注入方式详解流程

    2021-07-02 12:25:47
  • C语言数据结构之二叉树的非递归后序遍历算法

    2021-12-23 07:10:52
  • Android Studio 3.0后出现AAPT2与“android.enableAapt2”问题的解决方法

    2021-08-28 20:29:54
  • Android实现基于ViewPager的无限循环自动播放带指示器的轮播图CarouselFigureView控件

    2022-06-25 19:04:23
  • Android自定义相机Camera实现手动对焦的方法示例

    2022-08-23 14:45:11
  • FeignClient如何脱离eureka自定义URL

    2022-08-27 01:37:25
  • 你可知HashMap为什么是线程不安全的

    2021-12-10 20:14:59
  • Android GestureDetector实现手势滑动效果

    2023-10-01 04:37:50
  • 解决Java执行Cmd命令出现的死锁问题

    2023-06-15 09:54:56
  • C#机器入门学习之判断日报是否合格详解

    2023-03-24 01:55:08
  • Mybatis TypeHandler接口及继承关系示例解析

    2021-11-19 03:33:34
  • Android实现长截屏功能

    2022-03-02 15:20:27
  • Android中GridView布局实现整体居中方法示例

    2023-12-23 13:21:18
  • C#中值类型和引用类型的区别深度分析

    2022-07-21 21:29:26
  • java使用静态关键字实现单例模式

    2023-11-29 13:37:33
  • C#超市收银系统设计

    2023-06-21 00:00:09
  • Java实现批量下载选中文件功能

    2021-09-09 17:57:45
  • c#实现KTV点歌系统

    2023-10-17 23:54:56
  • asp之家 软件编程 m.aspxhome.com