我一直在寻找正确的数学公式,以根据价格列表中的最低和最高价格(int32)在画布中设置正确的 y 位置。
我希望你能帮我制定一个公式来解决我的问题。
我有一个画布控件,我想在其中画线来显示价格趋势。我有的是要绘制的价格表,
示例:10 20 30 40 50
列表中的最低和最高价格,当然还有画布控件。
到目前为止的公式是:
double currentPriceLineY = canvas.Height - (canvas.Height * (history.Price / highestPrice));
Run Code Online (Sandbox Code Playgroud)
使用此代码,我根据最高价格设置该线的 y 位置,
但现在我不知道如何将其与画布底部的最低价格结合起来,而最高价格位于画布的顶部,以及这两个点之间相对于最高和最低价格的其他价格。
我从昨天开始就陷入困境,决定向你们寻求帮助,希望你们能理解我的问题。
提前感谢避免者
首先,计算最低值和最高值之间的差(我在代码中将其称为范围)。然后对于每个值,减去最小值并除以范围。这将为您提供该值范围内的百分比。然后画线 - 请记住 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>
Run Code Online (Sandbox Code Playgroud)
代码:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)