mirror of
https://github.com/nsnail/spectre.console.git
synced 2025-06-20 21:58:16 +08:00
Add breakdown chart support
This also cleans up the bar chart code slightly and fixes some minor bugs that were detected in related code. Closes #244
This commit is contained in:

committed by
Patrik Svensson

parent
58400fe74e
commit
b64e016e8c
42
src/Spectre.Console/Widgets/Charts/BreakdownBar.cs
Normal file
42
src/Spectre.Console/Widgets/Charts/BreakdownBar.cs
Normal file
@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Spectre.Console.Rendering;
|
||||
|
||||
namespace Spectre.Console
|
||||
{
|
||||
internal sealed class BreakdownBar : Renderable
|
||||
{
|
||||
private readonly List<IBreakdownChartItem> _data;
|
||||
|
||||
public int? Width { get; set; }
|
||||
|
||||
public BreakdownBar(List<IBreakdownChartItem> data)
|
||||
{
|
||||
_data = data ?? throw new ArgumentNullException(nameof(data));
|
||||
}
|
||||
|
||||
protected override Measurement Measure(RenderContext context, int maxWidth)
|
||||
{
|
||||
var width = Math.Min(Width ?? maxWidth, maxWidth);
|
||||
return new Measurement(width, width);
|
||||
}
|
||||
|
||||
protected override IEnumerable<Segment> Render(RenderContext context, int maxWidth)
|
||||
{
|
||||
var width = Math.Min(Width ?? maxWidth, maxWidth);
|
||||
|
||||
// Chart
|
||||
var maxValue = _data.Sum(i => i.Value);
|
||||
var items = _data.ToArray();
|
||||
var bars = Ratio.Distribute(width, items.Select(i => Math.Max(0, (int)(width * (i.Value / maxValue)))).ToArray());
|
||||
|
||||
for (var index = 0; index < items.Length; index++)
|
||||
{
|
||||
yield return new Segment(new string('█', bars[index]), new Style(items[index].Color));
|
||||
}
|
||||
|
||||
yield return Segment.LineBreak;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user