如何在WPF中优化Canvas绘图?

时间:2017-07-17 10:05:58

标签: c# wpf canvas

如何在WPF中优化Canvas绘图,当我在程序“Paint”中有10000行时?当我画“Paint”时,我可以使用多少线条和圆圈,但在我的程序中agter + -10000我有滞后。 我创建了一个10000行的测试程序,当我在画布上移动鼠标矩形时,将位置更改为光标。 这里是代码

for (int i=0; i < 10000; i++)
        {
            Line l = new Line();
            l.Stroke = Brushes.Black;
            l.StrokeThickness = 1;
            l.X1 = 50+ privi;
            l.Y1 = 50 + privi;
            l.X2 = 100 ;
            l.Y2 = 100 + privi;
            MainCanvas.Children.Add(l);
            privi += 5;
}

在这里我动了

if (clicked)
        {
            Point p = Mouse.GetPosition(MainCanvas);
            rect.Margin = new Thickness(p.X-25, p.Y - 25, 0, 0);
        }
enter code here

更新

privi = 5;
Rectangle rect = new Rectangle();
rect.Fill = Brushes.Black;
rect.Width = 50;
rect.Height = 50;
MainCanvas.Children.Add(rect)

1 个答案:

答案 0 :(得分:-1)

我不知道你是否需要在同一个画布上使用直线和矩形,否则我发现在MainCanvas上的第二个透明画布中添加矩形可以提高反应性。

<Window x:Class="WpfApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="1080" Width="1024">
    <Canvas Name="MainCanvas" MouseMove="MainCanvas_MouseMove">
       <Canvas Name="RectCanvas" Background="Transparent" MouseMove="RectCanvas_MouseMove">
       </Canvas>
    </Canvas>
</Window>

public partial class MainWindow : Window
{
    double privi = 5;

    Rectangle rect;

    public MainWindow()
    {
        InitializeComponent();

        for (int i = 0; i < 10000; i++)
        {
            Line l = new Line();
            l.Stroke = Brushes.Black;
            l.StrokeThickness = 1;
            l.X1 = 50 + privi;
            l.Y1 = 50 + privi;
            l.X2 = 100;
            l.Y2 = 100 + privi;
            MainCanvas.Children.Add(l);
            privi += 5;
        }

        rect = new Rectangle();
        rect.Width = 50;
        rect.Height = 50;            
        rect.Fill = Brushes.Black;
        Canvas.SetLeft(rect, 0);
        Canvas.SetTop(rect, 0);
        SecondCanvas.Children.Add(rect);
    }

    private void RectCanvas_MouseMove(object sender, MouseEventArgs e)
    {
        //if (clicked)
        {
            Point p = Mouse.GetPosition(MainCanvas);
            rect.Margin = new Thickness(p.X - 25, p.Y - 25, 0, 0);
        }
    }
}