Reputation: 45
I am using canvas for drawing some shapes in WPF. XAML code:
<Canvas x:Name="canvas1"
Background="Transparent"
Margin="0,40,0,0"
MouseDown="canvas1_MouseDown"
MouseMove="canvas1_MouseMove"
MouseUp="canvas1_MouseUp"
KeyUp="canvas1_KeyUp" >
</Canvas>
In it I have three canvas events: "Down", "Move", "Up". I use them to draw a shape and then add it to canvas child. When i add multiple children it becomes slow.
Here is some sample code for adding a child:
Rectangle rect;
public void canvas1_MouseDown(object sender, MouseButtonEventArgs e)
{
rect = new Rectangle
{
StrokeDashArray = { 2,2 },
StrokeThickness = 1
};
Canvas.SetTop(rect, startPoint.Y);
}
public void canvas1_MouseMove(object sender, MouseButtonEventArgs e)
{ if(boolVariable){ canvas1.Children.Add(rect);
boolVariable=false}
rect.Width = w;
rect.Height = h;
Canvas.SetLeft(rect, x);
Canvas.SetTop(rect, y);
}
public void canvas1_Mouseup(object sender, MouseButtonEventArgs e)
{
rect = null;
}
Thats code which i use for adding different shapes.Kindly help me how i handle the speed issues. Thanks.
Upvotes: 0
Views: 578
Reputation: 15197
Your error is located here:
public void canvas1_MouseMove(object sender, MouseButtonEventArgs e)
{
canvas1.Children.Add(rect);
// ...
}
On each mouse movement, you add a new visual child to the Canvas
. Of course, at some point it will be slow because you probably add thousands of visual children.
Move this line to the canvas1_MouseDown
event handler.
Upvotes: 2