WPF仿LiveCharts实现饼图的绘制

目录
  • 前言
  • 一、PieControl.cs
  • 二、App.xaml
  • 三、MainWindow.xaml
  • 四、MainWindow.xaml.cs

每日一笑

下班和实习生一起回家,公交站等车,一乞丐把碗推向实习生乞讨。这时,实习生不慌不忙的说了句:“我不要你的钱,你这钱来的也不容易。”

前言

有小伙伴需要统计图。

效果预览(更多效果请下载源码体验)

一、PieControl.cs

using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using WpfPieControl.Models;

namespace WpfPieControl
{
    public class PieControl: Control
    {
        public ObservableCollection<PieSegmentModel> PieSegmentModels
        {
            get { return (ObservableCollection<PieSegmentModel>)GetValue(PieSegmentModelsProperty); }
            set { SetValue(PieSegmentModelsProperty, value); }
        }

        public static readonly DependencyProperty PieSegmentModelsProperty =
            DependencyProperty.Register("PieSegmentModels", typeof(ObservableCollection<PieSegmentModel>), typeof(PieControl), new UIPropertyMetadata(OnPieSegmentModelChanged));

        private static void OnPieSegmentModelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PieControl pieControl = d as PieControl;
            if (e.NewValue != null)
            {
                var array = e.NewValue as ObservableCollection<PieSegmentModel>;
                double angleNum = 0;
                foreach (var item in array)
                {
                    var color = new SolidColorBrush((Color)ColorConverter.ConvertFromString(pieControl.ColorArray[array.IndexOf(item)]));
                    item.Color = color;
                    item.StartAngle = angleNum;
                    item.EndAngle = angleNum + item.Value / 100 * 360;
                    angleNum = item.EndAngle;
                }
            }
        }
        /// <summary>
        /// colors
        /// </summary>
        private string[] ColorArray = new string[] { "#FDC006", "#607E89", "#2095F2", "#F34336" };

        /// <summary>
        /// 0~1
        /// </summary>
        public double ArcThickness
        {
            get { return (double)GetValue(ArcThicknessProperty); }
            set { SetValue(ArcThicknessProperty, value); }
        }

        public static readonly DependencyProperty ArcThicknessProperty =
            DependencyProperty.Register("ArcThickness", typeof(double), typeof(PieControl), new PropertyMetadata(1.0));

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

二、App.xaml

<Style TargetType="{x:Type local:PieControl}">
            <Setter Property="UseLayoutRounding" Value="True" />
            <!--<Setter Property="Background" Value="#252525"/>-->
            <Setter Property="Foreground" Value="White"/>
            <Setter Property="Width" Value="250"/>
            <Setter Property="Height" Value="250"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:PieControl}">
                        <ItemsControl Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"
                                      ItemsSource="{TemplateBinding PieSegmentModels}"
                                      Background="{TemplateBinding Background}">
                            <ItemsControl.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <Grid IsItemsHost="True"/>
                                </ItemsPanelTemplate>
                            </ItemsControl.ItemsPanel>
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <ed:Arc Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"
                                                ArcThickness="{Binding ArcThickness,RelativeSource={RelativeSource FindAncestor,AncestorType=local:PieControl}}" ArcThicknessUnit="Percent"
                                                EndAngle="{Binding EndAngle}"
                                                StartAngle="{Binding StartAngle}"
                                                Stretch="None"
                                                ToolTip="{Binding Name}"
                                                Stroke="{Binding ColorStroke}"
                                                StrokeThickness="2"
                                                Fill="{Binding Color}">
                                    </ed:Arc>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
</Style>

三、MainWindow.xaml

<Window x:Class="WpfPieControl.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfPieControl"
        mc:Ignorable="d"
        Title="微信公众号:WPF开发者" Height="450" Width="800">
    <StackPanel>
        <WrapPanel Margin="10">
            <local:PieControl PieSegmentModels="{Binding PieSegmentModels,RelativeSource={RelativeSource AncestorType=local:MainWindow}}" ArcThickness="1"/>
            <local:PieControl PieSegmentModels="{Binding PieSegmentModels,RelativeSource={RelativeSource AncestorType=local:MainWindow}}"
                                  Margin="4,0"
                                  ArcThickness="{Binding ElementName=PRAT_Slider,Path=Value}"/>
            <local:PieControl PieSegmentModels="{Binding PieSegmentModels,RelativeSource={RelativeSource AncestorType=local:MainWindow}}" ArcThickness="0.65"/>
        </WrapPanel>
        <Slider Maximum="0.9" Minimum="0.1" x:Name="PRAT_Slider" Margin="10" Width="200"/>
        <Button Content="更新" Click="Button_Click" VerticalAlignment="Bottom" Width="200"/>
    </StackPanel>
</Window>

四、MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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;
using WpfPieControl.Models;

namespace WpfPieControl
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public ObservableCollection<PieSegmentModel> PieSegmentModels
        {
            get { return (ObservableCollection<PieSegmentModel>)GetValue(PieSegmentModelsProperty); }
            set { SetValue(PieSegmentModelsProperty, value); }
        }

        public static readonly DependencyProperty PieSegmentModelsProperty =
            DependencyProperty.Register("PieSegmentModels", typeof(ObservableCollection<PieSegmentModel>), typeof(MainWindow), new PropertyMetadata(null));

        List<ObservableCollection<PieSegmentModel>> collectionList = new List<ObservableCollection<PieSegmentModel>>();
        public MainWindow()
        {
            InitializeComponent();

            PieSegmentModels = new ObservableCollection<PieSegmentModel>();
            var collection1 = new ObservableCollection<PieSegmentModel>();
            collection1.Add(new PieSegmentModel { Name = "一", Value = 10 });
            collection1.Add(new PieSegmentModel { Name = "二", Value = 20 });
            collection1.Add(new PieSegmentModel { Name = "三", Value = 25 });
            collection1.Add(new PieSegmentModel { Name = "四", Value = 45 });
            var collection2 = new ObservableCollection<PieSegmentModel>();
            collection2.Add(new PieSegmentModel { Name = "一", Value = 30 });
            collection2.Add(new PieSegmentModel { Name = "二", Value = 15 });
            collection2.Add(new PieSegmentModel { Name = "三", Value = 10 });
            collection2.Add(new PieSegmentModel { Name = "四", Value = 55 });
            collectionList.AddRange(new[] { collection1, collection2 });

            PieSegmentModels = collectionList[0];
        }
        bool isRefresh = false;
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (!isRefresh)
                PieSegmentModels = collectionList[1];
            else
                PieSegmentModels = collectionList[0];
            isRefresh = !isRefresh;

        }
    }
}

到此这篇关于WPF仿LiveCharts实现饼图的绘制的文章就介绍到这了,更多相关WPF饼图内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • WPF实现雷达扫描图的绘制详解

    目录 前言 制作思路 具体实现 前言 实现一个雷达扫描图. 源代码在TK_King/雷达 (gitee.com),自行下载就好了 制作思路 绘制圆形(或者称之轮) 绘制分割线 绘制扫描范围 添加扫描点 具体实现 首先我们使用自定义的控件.你可以使用vs自动添加,也可以手动创建类.注意手动创建时要创建Themes/Generic.xaml的文件路径哦. 控件继承自itemscontrol,取名叫做Radar. 我们第一步思考如何实现圆形或者轮,特别是等距的轮. 我们可以使用简单的itemscont

  • WPF实现手风琴式轮播图切换效果

    本文实例为大家分享了WPF实现轮播图切换效果的具体代码,供大家参考,具体内容如下 实现效果如下: 步骤: 1.自定义控件MyImageControl 实现图片的裁切和动画的赋值. public partial class MyImageControl : UserControl { public static readonly DependencyProperty ShowImageProperty = DependencyProperty.Register("ShowImage",

  • WPF图表LiveChart使用详解

    本文主要介绍LiveChart.WPF 中的图表的使用方法 类: 数据绑定, 数据显示样式等. 导入LiveChart.Wpf NuGet搜索LiveChart包, 安装LiveChart.Wpf即可. 引用LiveChart.Wpf 在使用的界面当中引用LiveChart.Wpf的类库 xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf" 以直方图.折线图为例, 都属于 CartesianChart 下的一种

  • WPF 自定义雷达图开发实例教程

    自定义雷达图表如下: 1.创建UserControl,名为"RadarChartControl" 前台: <UserControl x:Class="WpfApplication2.RadarChartControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/win

  • WPF使用DrawingContext实现二维绘图

    DrawingContext比较类似WinForm中的Graphics 类,是基础的绘图对象,用于绘制各种图形,它主要API有如下几种: 绘图API 绘图API一般形为DrawingXXX系列,常用的基础的绘图API有: DrawEllipse DrawGeometry DrawGlyphRun DrawImage DrawRectangle DrawRoundedRectangle 这些和GDI的API是非常相似的,WPF的API中另外还都有一个带动画的版本,不过一般很少用. 另外还有两个相对

  • WPF实现绘制统计图(柱状图)的方法详解

    目录 前言 实现代码 效果预览 前言 有小伙伴提出需要实现统计图. 由于在WPF中没有现成的统计图控件,所以我们自己实现一个. PS:有更好的方式欢迎推荐. 实现代码 一.创建 BasicBarChart.cs 继承 Control代码如下. BasicBarChart.cs实现思路如下 1.SeriesArray :存放展示集合 . 2.重写OnRender . 3.先绘制X轴线. 4.调用GetFormattedText()绘制底部类别. 5.调用GetFormattedText()绘制左侧

  • WPF仿LiveCharts实现饼图的绘制

    目录 前言 一.PieControl.cs 二.App.xaml 三.MainWindow.xaml 四.MainWindow.xaml.cs 每日一笑 下班和实习生一起回家,公交站等车,一乞丐把碗推向实习生乞讨.这时,实习生不慌不忙的说了句:“我不要你的钱,你这钱来的也不容易.” 前言 有小伙伴需要统计图. 效果预览(更多效果请下载源码体验) 一.PieControl.cs using System.Collections.ObjectModel; using System.Windows;

  • Python+matplotlib实现饼图的绘制

    目录 一.整理数据 二.创建饼图 三.爆炸效果 四.阴影效果 五.为饼图加上百分比 六.让饼图旋转不同的角度 七.为饼图添加边缘线 八.为饼图数据分组 一.整理数据 关于cnboo1.xlsx,我放在我的码云里,需要的朋友自行下载:cnboo1.xlsx films=['穿过寒冬拥抱你','反贪风暴5:最终章','李茂扮太子','误杀2','以年为单位的恋爱','黑客帝国:矩阵重启','雄狮少年','魔法满屋','汪汪队立大功大电影','爱情神话'] regions=['中国','英国','澳大

  • WPF仿微信实现截图功能的方法详解

    目录 前言 一.ScreenCut.cs 代码如下 二.ScreenCut.xaml 代码如下 三.ScreenCutExample.xaml 代码如下 每日一笑 肚子疼,去厕所排便,结果什么都没拉出来.看着自己坐在马桶上痛苦又努力却一无所获的样子,仿佛看到了自己平凡的一生. 前言 有小伙伴需要在软件反馈窗体增加截图功能需求,所以今天来实现一个仿微信的截图. 效果预览(更多效果请下载源码体验) 一.ScreenCut.cs 代码如下 using Microsoft.Win32; using Sy

  • WPF+WriteableBitmap实现高性能曲线图的绘制

    目录 一.前言 二.正文 三.运行效果 一.前言 之前分享过一期关于DrawingVisual来绘制高性能曲线的博客,今天再分享一篇通过另一种方式来绘制高性能曲线的方法,也就是通过WriteableBitmap的方式:具体的一些细节这里就不啰嗦了,同样是局部绘制的思想,滚动条拖动到哪里,就只绘制那一部分的曲线,直接贴代码:(该程序在英特尔11代CPU的电脑可能会遇到拖动滚动条曲线图卡住不动的情况,这个是显卡驱动的问题,官方已经修复了,遇到这问题的记得更新一下驱动) 二.正文 1.新建一个类,继承

  • iOS绘制3D饼图的实现方法

    实现核心 1.压缩饼图,使饼图有3D的效果,并不是真正的画了个3D圆柱 2.绘制厚度,带阴影效果,让看上去像是圆柱的高 3.路径添加好了,用颜色填充后绘制一下,添加阴影后还需绘制一遍 饼图添加阴影的思考 之前这加阴影的一段不是很明白,为啥设颜色和阴影都要draw一次 进过反复的测试,我自己分析了一下,每次draw一下想当于,把当前的设置画出来,再次draw就在这基础上,再画最近的设置,这里加颜色和阴影就像是一层一层的画上去.要是不draw的话,再设置颜色相当于重新设置了颜色,之前设置的颜色就无效

  • Python利用matplotlib实现饼图绘制

    目录 前言 1. 等高线图概述 什么是饼图? 饼图常用场景 绘制等饼图步骤 案例展示 2. 饼图属性 设置饼图的颜色 设置标签 设置突出部分 设置填入百分比数值 饼图旋转 设置阴影 3. 调整饼图的大小 4. 添加图例 5. 镂空饼图 总结 前言 众所周知,matplotlib.pyplot 提供绘制不同表格绘制方法,如使用plot()方法绘制折线,bar()绘制柱 在matplotlib.pyplot 中还有一种图表用于直观表示占比情况的饼图,在matplotlib官网上也列举出非常多关于饼图

  • 利用kotlin实现一个饼图实例代码

    前言 饼图是许多人最熟悉的图表类型,也是使用频率最高的图表类型之一,本文主要给大家介绍了关于利用kotlin实现饼图的相关内容,分享出来供大家参考学习,代码不难,所以打算用kotlin来实现,增加熟练度,下面来一起看看吧. 先看看做的是什么 看完图,我们来整理下思路 饼图居中,每块区域都是一个扇形,需要canvas.drawArc根据角度来绘制 需要path.arcTo定位到扇形弧度的一半来绘制折线的起点 通过canvas.drawPath绘制折线,折线的长度根据饼图大小来设置比例 通过canv

  • python ImageDraw类实现几何图形的绘制与文字的绘制

    python PIL图像处理模块中的ImageDraw类支持各种几何图形的绘制和文本的绘制,如直线.椭圆.弧.弦.多边形以及文字等. 下面直接通过示例来进行说明: #-*- coding: UTF-8 -*- import numpy as np from PIL import Image from PIL import ImageDraw from PIL import ImageFont def draw_test(): #生成深蓝色绘图画布 array = np.ndarray((480,

  • Java 在Excel中添加分离型饼图、环形图的方法

    一.概述 Excel中可支持多种不同类型的图表,本文介绍如何绘制分离型饼图和环形图.其中,分离型饼图的绘制可分为整体分离型(即设置饼图分离程度)和局部分离(即设置点爆炸型值)两种情况.下面将以Java程序代码介绍如何在Excel中实现以上图形. 二.程序环境 Spire.Xls.jar Jdk 1.8.0(版本>=1.6.0即可) IDEA 注:Jar使用的是Free Spire.XLS for Java(免费版)中的Spire.Xls.jar.编辑代码前,导入jar到Java程序,两种方法可导

随机推荐