不使用画布C#画线的最佳方法

时间:2015-08-20 07:55:57

标签: c# wpf line

我想知道从列表中以最大值绘制线条的最佳方法是不使用画布?

我已经确定了Max,Min和Median我想知道在不使用画布的情况下绘制线/点的最佳方法是什么?

public partial class SpectrumControl : UserControl
{
    private double Highest;
    private double Minimum;
    private double Median;
    private int Total;
    private int CellWidth;

    public int Width { get; set; }

    public SpectrumControl()
    {

        InitializeComponent();
    }

    public void Bind(KLayer klayer)
    {
        if (Width == 0)
        {
            Width = 300;
        }

        Highest = klayer.Values.Max();
        Minimum = klayer.Values.Min();
        Median = ((Highest - Minimum) / 2) + Minimum;
        Total = klayer.Values.Count;
        CellWidth = Width / Total;
        int rowNumber = 0;
        foreach (var item in klayer.Values)
        {
            var label = CreateLabel(item, rowNumber);
            Color backgroundColour = GetColour(item);
            stk1.Children.Add(label);
            rowNumber++;
        }
    }

    private Label CreateLabel(double item, int rowNumber)
    {

        var label = new Label()
        {
            Background = new SolidColorBrush(GetColour(item)),
            Width = CellWidth
        };
        return label;

    }

    private Color GetColour(double item)
    {
        byte a = Convert.ToByte(GetTransparency(item)*255);
        Color backgroundColour;
        if (item < Median)
        {
            backgroundColour = Color.FromArgb(a, 128, 128, 255);
        }
        else if (item > Median)
        {
            backgroundColour = Color.FromArgb(a, 255, 128, 128);
        }
        else
        {
            backgroundColour = Colors.White;
        }

        return backgroundColour;
    }

    private double GetTransparency(double item)
    {
        double x = Highest - Minimum;
        double difference;
        if (item > Median)
        {
            difference = item - Median;
        }
        else
        {
            difference = Median - item;
        }

        var fraction = difference / x;
        return fraction;
    }
}

1 个答案:

答案 0 :(得分:2)

好吧,假设您打算使用GridPanel或其他任何小组,实际上,您可以这样做:

var line = new Line();
line.Stroke = System.Windows.Media.Brushes.LightSteelBlue;
line.X1 = 1;
line.X2 = 50;
line.Y1 = 1;
line.Y2 = 50;
line.HorizontalAlignment = HorizontalAlignment.Left;
line.VerticalAlignment = VerticalAlignment.Center;
line.StrokeThickness = 2;
grid.Children.Add(line);

在XAML中可以实现同样的功能,但看起来您更喜欢在代码隐藏中工作,所以这就是我在这里发布的内容。

参考:https://msdn.microsoft.com/en-us/library/system.windows.shapes.line%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

我不确定你为什么要避免画布(好吧,为什么有人告诉你这样做)。我用帆布创造了很多情节。