Dispenser/DispenserUI/Views/Controls/Histogram.axaml.cs

72 lines
1.9 KiB
C#

using System;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Masuit.Tools;
namespace DispenserUI.Views.Controls;
public partial class Histogram : UserControl
{
public static readonly DirectProperty<Histogram, double[]> DataProperty =
AvaloniaProperty.RegisterDirect<Histogram, double[]>(
nameof(Data),
o => o.Data,
(o, v) => o.Data = v);
private double[] _data = Array.Empty<double>();
public Histogram()
{
InitializeComponent();
}
public double[] Data
{
get => _data;
set
{
SetAndRaise(DataProperty, ref _data, value);
InvalidateVisual(); // 重绘控件
}
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
protected override void OnSizeChanged(SizeChangedEventArgs e)
{
base.OnSizeChanged(e);
InvalidateVisual();
}
public override void Render(DrawingContext context)
{
base.Render(context);
if (Data.IsNullOrEmpty()) return; // 如果没有数据,则不绘制
var width = Bounds.Width; // 控件宽度
var height = Bounds.Height; // 控件高度
var maxDataValue = Data.Max();
var columnsCount = Data.Length;
var spaceRatio = 0.2; // 柱体间空隙占柱体宽度的比例
var columnWidth = width / (columnsCount + columnsCount * spaceRatio - spaceRatio); // 计算柱体宽度
var spaceWidth = columnWidth * spaceRatio; // 计算柱体间空隙宽度
for (var i = 0; i < columnsCount; i++)
{
var columnHeight = Data[i] / maxDataValue * height; // 根据数据值计算柱体高度
var rect = new Rect(i * (columnWidth + spaceWidth), height - columnHeight, columnWidth, columnHeight);
context.FillRectangle(Brushes.Blue, rect); // 绘制柱体
}
}
}