最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

WPF實(shí)現(xiàn)繪制統(tǒng)計(jì)圖(柱狀圖)的方法詳解

 更新時(shí)間:2022年07月26日 10:21:02   作者:驚鏵  
這篇文章主要為大家詳細(xì)介紹了如何基于WPF實(shí)現(xiàn)實(shí)現(xiàn)統(tǒng)計(jì)圖(柱狀圖)的繪制,文中的示例代碼簡潔易懂,對我們學(xué)習(xí)WPF有一定幫助,感興趣的可以了解一下

前言

有小伙伴提出需要實(shí)現(xiàn)統(tǒng)計(jì)圖。 

由于在WPF中沒有現(xiàn)成的統(tǒng)計(jì)圖控件,所以我們自己實(shí)現(xiàn)一個(gè)。

PS:有更好的方式歡迎推薦。

實(shí)現(xiàn)代碼

一、創(chuàng)建 BasicBarChart.cs 繼承 Control代碼如下。

BasicBarChart.cs實(shí)現(xiàn)思路如下

1、SeriesArray :存放展示集合 。

2、重寫OnRender 。

3、先繪制X軸線。

4、調(diào)用GetFormattedText()繪制底部類別。

5、調(diào)用GetFormattedText()繪制左側(cè)標(biāo)尺。

6、DrawingContext繪制Line的時(shí)候會(huì)發(fā)虛,以下方法可以避免

 var d = Pen.Thickness / 2;

 var guidelines = new GuidelineSet(new[] { d }, new[] { d });

drawingContext.PushGuidelineSet(guidelines);

或者調(diào)用

SnapDrawingExtensions.DrawSnappedLinesBetweenPoints()

避免畫線發(fā)虛。

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WPFDevelopers.Controls
{
    public class BasicBarChart : Control
    {
        public IEnumerable<KeyValuePair<string, double>> SeriesArray
        {
            get { return (IEnumerable<KeyValuePair<string, double>>)GetValue(SeriesArrayProperty); }
            set { SetValue(SeriesArrayProperty, value); }
        }

        public static readonly DependencyProperty SeriesArrayProperty =
            DependencyProperty.Register("SeriesArray", typeof(IEnumerable<KeyValuePair<string, double>>), typeof(BasicBarChart), new UIPropertyMetadata(SeriesArrayChanged));
        private static void SeriesArrayChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            BasicBarChart radarChart = d as BasicBarChart;
            if (e.NewValue != null)
                radarChart.InvalidateVisual();
        }


        static BasicBarChart()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(BasicBarChart), new FrameworkPropertyMetadata(typeof(BasicBarChart)));
        }
        protected override void OnRender(DrawingContext drawingContext)
        {
            //base.OnRender(drawingContext);
            if (SeriesArray == null || SeriesArray.Count() == 0)
                return;
            SnapsToDevicePixels = true;
            UseLayoutRounding = true;
            var brushConverter = new BrushConverter();
            var myPen = new Pen
            {
                Thickness = 1,
                Brush = (Brush)brushConverter.ConvertFromString("#6E7079")
            };
            myPen.Freeze();

            //var d = myPen.Thickness / 2;
            //var guidelines = new GuidelineSet(new[] { d }, new[] { d });
            //drawingContext.PushGuidelineSet(guidelines);

            var h = this.ActualHeight / 2 + 160;
            var w = this.ActualWidth / 2;
            var startX = w / 3;
            var width = SeriesArray.Count() * 120 + startX;
            //drawingContext.DrawLine(myPen, new Point(startX, h), new Point(width, h));
            var stratNum = 0;

            SnapDrawingExtensions.DrawSnappedLinesBetweenPoints(drawingContext,myPen,myPen.Thickness, new Point(startX, h), new Point(width, h));
            var formattedText = GetFormattedText(stratNum.ToString());
            drawingContext.DrawText(formattedText, new Point(startX - formattedText.Width * 2 - 10, h - formattedText.Height / 2));
            var x = startX;
            //var y = h + d;
            var y = h + myPen.Thickness;
            var points = new List<Point>();
            var rectBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#5470C6"));
            for (int i = 0; i < SeriesArray.Count() + 1; i++)
            {
                //drawingContext.DrawLine(myPen, new Point(x, y), new Point(x, y + 4));
                points.Add(new Point(x, y));
                points.Add(new Point(x, y + 4));
                x = x + 120;
            }
            SnapDrawingExtensions.DrawSnappedLinesBetweenPoints(drawingContext, myPen, myPen.Thickness, points.ToArray());

            var xAxisPen = new Pen
            {
                Thickness = 1,
                Brush = (Brush)brushConverter.ConvertFromString("#E0E6F1")
            };
            xAxisPen.Freeze();
            var xAxis = h - 80;
            int max = Convert.ToInt32(SeriesArray.Max(kvp => kvp.Value));
            max = (max / 50 + (max % 50 == 0 ? 0 : 1)) * 50 / 50;
            int min = Convert.ToInt32(SeriesArray.Min(kvp => kvp.Value));
            points.Clear();
            for (int i = 0; i < max; i++)
            {
                //drawingContext.DrawLine(xAxisPen, new Point(startX, xAxis), new Point(width, xAxis));
                points.Add(new Point(startX, xAxis));
                points.Add(new Point(width, xAxis));
                stratNum += 50;
                formattedText = GetFormattedText(stratNum.ToString());
                drawingContext.DrawText(formattedText, new Point(startX - formattedText.Width - 10, xAxis - formattedText.Height / 2));
                xAxis = xAxis - 80;
            }
            SnapDrawingExtensions.DrawSnappedLinesBetweenPoints(drawingContext, xAxisPen, xAxisPen.Thickness, points.ToArray());

            x = startX;
            var rectWidth = 85;
            var rectHeight = 0D;
            for (int i = 0; i < SeriesArray.Count(); i++)
            {
                formattedText = GetFormattedText(SeriesArray.ToList()[i].Key);
                drawingContext.DrawText(formattedText, new Point(x + 120 / 2 - formattedText.Width / 2, y + 4));
                var _value = SeriesArray.ToList()[i].Value;
                //rectHeight = _value * 200;
                rectHeight = (_value - 0) / (stratNum - 0) * (80 * max);
                //rectHeight = (stratNum - _value) / 100 * stratNum;
                drawingContext.DrawRectangle(rectBrush, null, new Rect(x + (120 - 85) / 2, h - rectHeight, rectWidth, rectHeight));
                x = x + 120;
            }
        }
        FormattedText GetFormattedText(string text)
        {
            var brushConverter = new BrushConverter();
            return new FormattedText(
                 text,
                 CultureInfo.CurrentCulture,
                 FlowDirection.LeftToRight,
                 new Typeface(new FontFamily("Microsoft YaHei"), FontStyles.Normal, FontWeights.UltraLight, FontStretches.Normal),
                 12, (Brush)brushConverter.ConvertFromString("#6E7079"))
            {
                MaxLineCount = 1,
                TextAlignment = TextAlignment.Justify,
                Trimming = TextTrimming.CharacterEllipsis
            };
        }
    }
    public static class SnapDrawingExtensions
    {
        public static void DrawSnappedLinesBetweenPoints(this DrawingContext dc,
            Pen pen, double lineThickness, params Point[] points)
        {
            var guidelineSet = new GuidelineSet();
            foreach (var point in points)
            {
                guidelineSet.GuidelinesX.Add(point.X);
                guidelineSet.GuidelinesY.Add(point.Y);
            }
            var half = lineThickness / 2;
            points = points.Select(p => new Point(p.X + half, p.Y + half)).ToArray();
            dc.PushGuidelineSet(guidelineSet);
            for (var i = 0; i < points.Length - 1; i = i + 2)
            {
                dc.DrawLine(pen, points[i], points[i + 1]);
            }
            dc.Pop();
        }
    }
}

如何換算出統(tǒng)計(jì)條占比如下:

二、創(chuàng)建BasicBarChartExample.xaml代碼如下

<UserControl x:Class="WPFDevelopers.Samples.ExampleViews.BasicBarChartExample"
             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/yanjinhuagood/WPFDevelopers"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid Background="Gainsboro">
        <Border
            Height="500"
            Background="White"
            Margin="30,0">
            <Grid Margin="20,10">
                
                <Grid.RowDefinitions>
                    <RowDefinition Height="40" />
                    <RowDefinition />
                    <RowDefinition Height="auto" />
                </Grid.RowDefinitions>
                <WrapPanel HorizontalAlignment="Right">
                    <Rectangle
                        Width="6"
                        Height="26"
                        Fill="Black" />
                    <TextBlock
                        Padding="10,0"
                        FontSize="24"
                        FontWeight="Black"
                        Text="{Binding KeyBarChart, RelativeSource={RelativeSource AncestorType=local:BasicBarChartExample}}" />
                </WrapPanel>
                <wpfdev:BasicBarChart
                     Grid.Row="1"
                    SeriesArray="{Binding SeriesModels, RelativeSource={RelativeSource AncestorType=local:BasicBarChartExample}}"/>
                <Button
                    Grid.Row="2"
                    Width="200"
                    VerticalAlignment="Bottom"
                    Click="Button_Click"
                    Content="刷新"
                    Style="{StaticResource PrimaryButton}" />
            </Grid>
        </Border>
    </Grid>
</UserControl>

三、創(chuàng)建BasicBarChartExample.xaml.cs代碼如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFDevelopers.Samples.ExampleViews
{
    /// <summary>
    /// BasicBarChartExample.xaml 的交互邏輯
    /// </summary>
    public partial class BasicBarChartExample : UserControl
    {
        public IEnumerable<KeyValuePair<string, double>> SeriesModels
        {
            get { return (IEnumerable<KeyValuePair<string, double>>)GetValue(SeriesModelsProperty); }
            set { SetValue(SeriesModelsProperty, value); }
        }

        public static readonly DependencyProperty SeriesModelsProperty =
            DependencyProperty.Register("SeriesModels", typeof(IEnumerable<KeyValuePair<string, double>>), typeof(BasicBarChartExample), new PropertyMetadata(null));


        Dictionary<string, IEnumerable<KeyValuePair<string, double>>> keyValues = new Dictionary<string, IEnumerable<KeyValuePair<string, double>>>();
        public string KeyBarChart
        {
            get { return (string)GetValue(KeyBarChartProperty); }
            set { SetValue(KeyBarChartProperty, value); }
        }
        public static readonly DependencyProperty KeyBarChartProperty =
     DependencyProperty.Register("KeyBarChart", typeof(string), typeof(BasicBarChartExample), new PropertyMetadata(null));
        private int _index = 0;
        public BasicBarChartExample()
        {
            InitializeComponent();
            var Models1 = new[]
            {
                new KeyValuePair<string, double>("Mon", 120),
                new KeyValuePair<string, double>("Tue", 130),
                new KeyValuePair<string, double>("Wed", 160),
                new KeyValuePair<string, double>("Thu", 140),
                new KeyValuePair<string, double>("Fri", 200) ,
                new KeyValuePair<string, double>("Sat", 80) ,
                new KeyValuePair<string, double>("Sun", 90) ,
            };
            keyValues.Add("到訪數(shù)", Models1);
            var Models2 = new[]
            {
                new KeyValuePair<string, double>("蛐蛐", 120),
                new KeyValuePair<string, double>("常威", 170),
                new KeyValuePair<string, double>("來福", 30),
                new KeyValuePair<string, double>("包龍星", 200),
                new KeyValuePair<string, double>("包有為", 100) ,
                new KeyValuePair<string, double>("雷豹", 180) ,
                new KeyValuePair<string, double>("方唐鏡", 90) ,
            };
            keyValues.Add("能力值", Models2);

            SeriesModels = keyValues.ToList()[0].Value;
            KeyBarChart = keyValues.ToList()[0].Key;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _index++;
            if (_index >= keyValues.Count)
            {
                _index = 0;
            }
            SeriesModels = keyValues.ToList()[_index].Value;
            KeyBarChart = keyValues.ToList()[_index].Key;
        }
    }
}

效果預(yù)覽

以上就是WPF實(shí)現(xiàn)繪制統(tǒng)計(jì)圖(柱狀圖)的方法詳解的詳細(xì)內(nèi)容,更多關(guān)于WPF統(tǒng)計(jì)圖的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • C#/VB.NET實(shí)現(xiàn)創(chuàng)建PDF/UA文件的示例代碼

    C#/VB.NET實(shí)現(xiàn)創(chuàng)建PDF/UA文件的示例代碼

    PDF/UA,即Universally?Accessible?PDF,該格式的PDF文件是于2012年8月以ISO標(biāo)準(zhǔn)14289-1發(fā)布的、具有普遍可訪問的PDF文檔標(biāo)準(zhǔn)。本文將用C#實(shí)現(xiàn)DF/UA文件的創(chuàng)建,需要的可以參考一下
    2022-08-08
  • 淺談C# 類的繼承

    淺談C# 類的繼承

    本文主要介紹了C# 類的繼承相關(guān)知識。具有很好的參考價(jià)值,下面跟著小編一起來看下吧
    2017-01-01
  • WinForm DataGridView控件隔行變色的小例子

    WinForm DataGridView控件隔行變色的小例子

    WinForm的DataGridView控件設(shè)置行的顏色
    2013-03-03
  • C# 最齊全的上傳圖片方法

    C# 最齊全的上傳圖片方法

    本文主要介紹了C# 最齊全的上傳圖片方法,方法里包括了圖片大小限制、圖片尺寸、文件內(nèi)容等等的判斷。具有很好的參考價(jià)值,下面跟著小編一起來看下吧
    2017-01-01
  • c# 繪制中國象棋棋盤與棋子

    c# 繪制中國象棋棋盤與棋子

    這篇文章主要介紹了c# 繪制中國象棋棋盤與棋子,文中實(shí)例代碼非常詳細(xì),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • VS2019配置OpenCV4.1.0詳細(xì)教程與測試代碼(推薦)

    VS2019配置OpenCV4.1.0詳細(xì)教程與測試代碼(推薦)

    這篇文章主要介紹了VS2019配置OpenCV4.1.0詳細(xì)教程與測試代碼,本文通過截圖實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-03-03
  • unity實(shí)現(xiàn)攝像頭跟隨

    unity實(shí)現(xiàn)攝像頭跟隨

    把這個(gè)腳本賦給你的攝像機(jī),再把游戲角色賦給character變量,之后就能實(shí)現(xiàn)攝像機(jī)平滑的跟隨player在地球的任一角落了。有需要的小伙伴可以參考下。
    2015-03-03
  • C#內(nèi)插字符串的簡單使用

    C#內(nèi)插字符串的簡單使用

    這篇文章主要為大家詳細(xì)介紹了C#內(nèi)插字符串的使用方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-11-11
  • C#正則表達(dá)式匹配與替換字符串功能示例

    C#正則表達(dá)式匹配與替換字符串功能示例

    這篇文章主要介紹了C#正則表達(dá)式匹配與替換字符串功能,結(jié)合具體實(shí)例形式分析了C#字符串正則替換相關(guān)類、方法的使用技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2017-06-06
  • .Net多進(jìn)程通信共享內(nèi)存映射文件Memory?Mapped

    .Net多進(jìn)程通信共享內(nèi)存映射文件Memory?Mapped

    這篇文章主要介紹了.Net多進(jìn)程通信共享內(nèi)存映射文件Memory?Mapped的使用示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-04-04

最新評論

额敏县| 西贡区| 武冈市| 班戈县| 临桂县| 阿坝| 吉首市| 石景山区| 灵武市| 闽侯县| 贵溪市| 许昌市| 襄垣县| 武清区| 元氏县| 平乡县| 嵊泗县| 潍坊市| 舟山市| 屏边| 广灵县| 和静县| 深水埗区| 正安县| 深圳市| 泗阳县| 丰都县| 舟山市| 奉节县| 乌鲁木齐市| 开原市| 临沂市| 洛川县| 吴川市| 榕江县| 金寨县| 孟州市| 葵青区| 清水县| 台州市| 东海县|