首先,计算最小值和最大值之间的差值(我在代码中将其称为范围)。然后对于每个值,从中减去最小值并除以范围。这将为您提供该值范围内的百分比。然后画线 - 请记住,0 位于顶部,canvas.Height 位于底部。在代码中,我反转了百分比来解决这个问题。
我还在该行上添加了一个 TextBlock,这样您就可以看到哪一行的值。
下面是它的实现:
XAML:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300">
<Window.Resources>
</Window.Resources>
<Grid>
<Canvas Background="Beige" Name="canvas" Height="200" Width="200" />
</Grid>
</Window>
代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
int highestPrice = 65;
List<int> vals = new List<int>() { 10, 20, 30, 40, 50 };
int min = vals.Min();
int max = vals.Max();
max = highestPrice > max ? highestPrice : max;
double range = max - min;
// Draw max in red
Color c = new Color() { ScA = 1, ScR = 1, ScG = 0, ScB = 0 };
// y = 0 is at the top of the canvas
var line = new Line() { X1 = 0, Y1 = 0, X2 = canvas.Width, Y2 = 0, Stroke = new SolidColorBrush(c), StrokeThickness = 2.0 };
canvas.Children.Add(line);
// Add txt so we can visualize better
var txt = new TextBlock() { Text = max.ToString() };
Canvas.SetLeft(txt, canvas.Width / 2);
Canvas.SetTop(txt, 0 - 9);
canvas.Children.Add(txt);
foreach (int val in vals)
{
double percent = 1.0 - ((val - min)/range); // 0 is at the top, so invert it by doing 1.0 - xxx
double y = percent*canvas.Height;
// Draw line in a shade of blue/green
c = new Color() { ScA = 1, ScR = 0, ScG = 0.5f, ScB = (float)percent };
line = new Line() { X1 = 0, Y1 = y, X2 = canvas.Width, Y2 = y, Stroke = new SolidColorBrush(c), StrokeThickness = 2.0 };
canvas.Children.Add(line);
// Add txt so we can visualize better
txt = new TextBlock() { Text = val.ToString() };
Canvas.SetLeft(txt, canvas.Width / 2);
Canvas.SetTop(txt, y - 9);
canvas.Children.Add(txt);
}
}
}