Drawing multiple rectangles chokes my WPF app - c#

I am working in my own editor for making WPF forms. My issue is that I am having the worst time selecting multiple controls (buttons, labels, etc) and dragging them smoothly across the main window. My application chokes when I try to drag, oh say, 20 selected buttons at the same time.
I found that the culprit is the fact that I am drawing multiple rectangles for each object as they are being dragged and this function is being called in the MouseMove event.
void ControlObjectControl_MouseMove(object sender, MouseEventArgs e)
{
if (newPosition != oldPosition)
{
DragSelection(newPosition);
}
}
private void DragSelection(Point newPosition)
{
foreach (FrameworkElement item in designer.SelectionService.CurrentSelection)
{
if (item is ObjectControl)
(item as ObjectControl).m_ParentControlObject.Position = new System.Drawing.Rectangle() { X = X, Y = Y, Width = (int)item.Width, Height = (int)item.Height };
//..There's code that calculates the item's position and dimensions
}
}
How do I make it to where it only draws the rectangle once and I am still able to see my selected object(s) move smoothly when I drag them?

I did something similar in my application except I used a TranslateTransform to move my elements. Each "frame" (every mouse move) that I was dragging, I got the position of the mouse and compared that to the previous position of the mouse. I would then set a new TranslateTransform X/Y values equal to the X/Y mouse position change and then would give that to the RenderTransform of each object I wanted to move. Something like:
void ControlObjectControl_MouseMove(object sender, MouseEventArgs e)
{
if (dragging)
{
// Get the change in Location
mouseLocation = Mouse.GetPosition();
Point deltaLocation = mouseLocation - previousLocation;
// Make a new transform
TranslateTransform transform = new TranslateTransform();
transform.X = deltaLocation.X;
transform.Y = deltaLocation.Y;
// Apply the transform
// foreach thing
thing.RenderTransform = transform;
// set previous location
previousLocation = mouseLocation;
}
}
Now your objects only get drawn once and only their positions get changed. Hope this helps

Related

Stop System.Windows.Shapes.Rectangle inertia if collision with another shape happens in WPF touchscreen app

I am working on touchscreen app. This app is for a certain industry, but the general ideals are all that is needed to explain issue. To start, im doing a crash course on WPF and am allowing a user to add a new command (Shape - Rectangle) then will assign functions to it. Example, they can add one, then add second, then a third and so on positioning them where they want.
What i would like to find out is how to tell the API when inertia is occurring and say a user touches a shape then flings it across screen, for the event to not only complete when it reaches the edge of the screen (already does this), but also if it intersects or hits another shape. Below is the general code for a quick basic proof of concept.
void Window_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
try
{
// Get the Rectangle and its RenderTransform matrix.
Rectangle rectToMove = e.OriginalSource as Rectangle;
Matrix rectsMatrix = ((MatrixTransform)rectToMove.RenderTransform).Matrix;
// Rotate the Rectangle.
rectsMatrix.RotateAt(e.DeltaManipulation.Rotation,
e.ManipulationOrigin.X,
e.ManipulationOrigin.Y);
// Resize the Rectangle. Keep it square
// so use only the X value of Scale.
rectsMatrix.ScaleAt(e.DeltaManipulation.Scale.X,
e.DeltaManipulation.Scale.X,
e.ManipulationOrigin.X,
e.ManipulationOrigin.Y);
// Move the Rectangle.
rectsMatrix.Translate(e.DeltaManipulation.Translation.X,
e.DeltaManipulation.Translation.Y);
// Apply the changes to the Rectangle.
rectToMove.RenderTransform = new MatrixTransform(rectsMatrix);
Rect containingRect =
new Rect(((FrameworkElement)e.ManipulationContainer).RenderSize);
Rect shapeBounds =
rectToMove.RenderTransform.TransformBounds(
new Rect(rectToMove.RenderSize));
// Check if the rectangle is completely in the window.
// If it is not and intertia is occuring, stop the manipulation.
if (e.IsInertial && !containingRect.Contains(shapeBounds))
{
e.Complete();
}
if (e.IsInertial)
{
//convert current moving rect to new rect drawing type
var tempRect = new Rect(Canvas.GetLeft(rectToMove), Canvas.GetTop(rectToMove), rectToMove.Width, rectToMove.Height);
//we need to convert SytsemWindows.Shapes.Rectablge to SystemWindows.Drawing.Rect first
//List<System.Windows.Shapes.Rectangle> removeCurrent = Commands.Where(r => r != rectToMove).ToList();
//List<System.Windows.Rect> coordinates = Commands.Where(r => r.Name != rectToMove.Name).Select(r => new Rect(Canvas.GetLeft(r), Canvas.GetTop(r), r.Width, r.Height)).ToList();
List<System.Windows.Rect> recs = new List<Rect>();
List<Rectangle> test = Commands.Where(r => r.Name != rectToMove.Name).ToList();
foreach (System.Windows.Shapes.Rectangle re in test)
{
if (re != rectToMove)
{
recs.Add(new Rect(Canvas.GetLeft(re), Canvas.GetTop(re), re.Width, re.Height));
}
}
//if rect item is in motion inertia and it intersects with any of pre made command rects, then stop.
if (recs.Any(c => c.InteriorIntersectsWith(tempRect)))
{
//There is overlapping
e.Complete();
}
}
}
catch(Exception ex)
{
}
e.Handled = true;
}
The problem is inertia works fine. Once a second shape is then added to the canvas, inertia no longer works. The user can click and drag them but when trying to flick the shapes they stop instantly as if it reports from all positions that it is intersecting with another shape even when they are no where near each other. Any ideas on what i am doing wrong?

Drag Ovalshape across form

So I have a bit of a problem with moving Ovalshapes around a form. The goal is to have a circle move within the bounds of two other circles, one placed inside the other and the moving circle essentially moving around them.
I am having trouble moving the circle with the mouse. Whenever I click and hold the circle, the circle moves to the coordinates of the location I clicked on the circle, such that if I click in the middle of an Ovalshape of size 10, it would set the circle's location to (5,5).
Here is what I have:
public partial class Form1 : Form
{
int smallRadius;
int largeRadius;
int movingRadius;
int distanceFromCenterToLocation;
bool mouseDown;
Point movingCenter;
Point returnPoint;
public Form1()
{
mouseDown = false;
InitializeComponent();
smallRadius = (ovalShape1.Right - ovalShape1.Left) / 2;
largeRadius = (ovalShape2.Right - ovalShape2.Left) / 2;
Point center = new Point(ovalShape1.Left + smallRadius, ovalShape1.Top + smallRadius);
ovalShape3.Height = largeRadius - smallRadius;
ovalShape3.Width = largeRadius - smallRadius;
movingRadius = (ovalShape3.Right - ovalShape3.Left) / 2;
ovalShape3.Location = new Point(center.X - (movingRadius), center.Y - largeRadius);
movingCenter = new Point(ovalShape3.Left + movingRadius, ovalShape3.Top + movingRadius);
distanceFromCenterToLocation = Convert.ToInt32(Math.Sqrt(Math.Pow(movingRadius, 2.0) + Math.Pow(movingRadius, 2.0)));
int middleRadius = center.X - movingCenter.X;
}
private void ovalShape3_MouseUp(object sender, MouseEventArgs e)
{
mouseDown = false;
}
private void ovalShape3_MouseDown(object sender, MouseEventArgs e)
{
mouseDown = true;
}
private void ovalShape3_MouseMove(object sender, MouseEventArgs e)
{
if (mouseDown)
{
ovalShape3.Location = e.Location;
}
}
}
For some reason OvalShape isn't derived from Control and doesn't behave like a control.
When a control receives a mouse event the Location property of the MouseEventArgs holds the coordinates relative to the upper-left corner of the form. Shapes however receive the coordinates relative to their own upper-left corner.
When a mouse button is pressed over a control it will capture the mouse so that subsequent events are sent to the same control until you release the button. Shapes only receive mouse events if the mouse is over the shape no matter if a mouse button is pressed. Once you move the mouse to the top or left the shape doesn't receive any mouse events. Therefore the shape doesn't follow the mouse and also the MouseUp event is not handled.
All shapes in a form are embedded in a single control of type ShapeContainer. This is created automatically when you add a shape to a form in the Visual Studio designer. To get the expected behavior you need to find that ShapeContainer (probably called shapeContainer1) and handle its mouse events instead:
public Form1()
{
InitializeComponent();
// do your initialization
...
// assign the events to the ShapeContainer
// don't forget to remove the handlers from ovalShape3 in the designer!!!
ShapeContainer container = ovalShape3.Parent;
container.MouseUp += ovalShape3_MouseUp;
container.MouseDown += ovalShape3_MouseDown;
container.MouseMove += ovalShape3_MouseMove;
}

Getting X,Y coordinates/position of slider

I need to get the [X,Y] positions of a slider.
I already tried the function "PointFromScreen" but I didn't get any result.
Anyone?
Thanks
private void SliderPosition(object sender)
{
Slider slider = (Slider)sender;
int x = (int)slider.Value;
Point x1 = Point.Parse(x);
Point slider_point = slider.PointFromScreen(x1);
}
UPDATE and more clear doubt:
I have a video going through, and a slide that is dependent of the number of frames.
Video format is 640x480, slider is defined in terms of frames!
I need to know, when the right button is pushed in the video image, the position[X,Y] of the slider so that I can draw a line in a Canvas that is beneath the video.
I think it's clear now. Going through the library, the only parameter I can find is the slider.value but that doesn't make my case.
Source code of my try:
private void Slider_position(object sender, System.Windows.Controls.Slider e, System.Windows.Input.MouseEventArgs e1)
{
if (e1.RightButton == MouseButtonState.Pressed)
{
Line line = new Line();
line.X1 = e. //something, i would get here the coordinates X,Y of slider here
// calculation from slider position to canvas position
// draw a line of the height of the canvas here after
}
}
Try using MouseClick() as this will give you the mouse positions, from the The AutoIt Window Info.

TranslateTransform offsets element a bit too much after multiple transforms in Windows 8 store application

I have a draggable element in a StackPanel in a Windows 8 store app. My goal is simple: drag the item somewhere on the screen and immediately after the user stops dragging it the element should return to its original starting position.
I have the following code which is meant to accomplish this task:
private void grdCover_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
{
Grid coverControl = sender as Grid;
double xOffset = -e.Cumulative.Translation.X;
double yOffset = -e.Cumulative.Translation.Y;
if (coverControl.RenderTransform is TranslateTransform)
{
TranslateTransform existingTransform = coverControl.RenderTransform as TranslateTransform;
existingTransform.X += xOffset;
existingTransform.Y += yOffset;
}
else
{
TranslateTransform transform = new TranslateTransform();
transform.X = xOffset;
transform.Y = yOffset;
coverControl.RenderTransform = transform;
}
}
The code sort of works. The screen looks like this upon application start:
The top element, which looks like a H is well aligned with the bottom element which looks like a U. When I first drag the H element it jumps back to its well aligned position, or at least any misalignment is so little that it's hardly perceivable to the naked eye. As I keep dragging and releasing the H element it gets more and more misaligned like this:
After 15-20 dragging moves the H element gets completely misplaced:
The problem might be due to some rounding error of the double values in the Point objects when they are translated into pixels, but that's only a wild guess. Also, on a high resolution device, such as my PC it takes more moves for the misalignment to become visible than on a lower resolution one, such as the Windows Simulator in Visual Studio.
Some other code that may be related to this issue:
I perform the dragging operation with the following code:
private void Grid_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
TranslateTransform translateTransform = (sender as Grid).RenderTransform as TranslateTransform;
translateTransform.X += e.Delta.Translation.X;
translateTransform.Y += e.Delta.Translation.Y;
}
I also have the following event handler in place to stop the element from moving too much on the screen after the user is done dragging the element:
private void grdCover_ManipulationInertiaStarting(object sender, ManipulationInertiaStartingRoutedEventArgs e)
{
e.TranslationBehavior.DesiredDeceleration = 10000000000000000;
e.Handled = true;
}
In case you're wondering I wanted to set the desired deceleration to Double.Max to block any further "sliding" movement on the screen but I got an exception saying it was out of bounds. So instead I chose this arbitrary large value.
I have no extra margins or padding on the layout root or the element to be moved or its container.
Any ideas are welcome.
Thanks, Andras
OK, I got it to work. The problem was that there was a slight mismatch between the Point coordinates in the following code bits:
TranslateTransform translateTransform = (sender as Grid).RenderTransform as TranslateTransform;
translateTransform.X += e.Delta.Translation.X;
translateTransform.Y += e.Delta.Translation.Y;
and
double xOffset = -e.Cumulative.Translation.X;
double yOffset = -e.Cumulative.Translation.Y;
The solution was to retrieve the value of
e.Delta.Translation.X
and
e.Delta.Translation.Y
and assign their values to the variables xOffset and yOffset. Retrieving the values of
e.Cumulative.Translation.X
and
e.Cumulative.Translation.Y
gave slightly different coordinates so the element kept jumping back to the wrong location.

Performance issue of DrawingVisual following cursor while using onMouseMove event

I'm busy with a small application in which I want to display information at the location of the cursor when it hoovers over a Canvas. The Canvas in question is a custom one (inherited from Canvas) which provides functionality to add DrawingVisuals (as shown in basically every tutorial on displaying large amounts of geometric shapes on a canvas).
I would like to display a vertical line and horizontal line as well as the local coordinates (p in the code below) which are directly derived from the canvas coordinates (v). At the moment I'm rendering these objects at position (0,0) and use offset during the OnMouseMove event to update their location.
The horizontal and vertical lines are rendered in the DrawingVisual _cursor and the location in local y,z-coordinates in _info.
private void oCanvas_MouseMove(object sender, MouseEventArgs e)
{
#region 1. Get location data
System.Windows.Vector v = (System.Windows.Vector)e.GetPosition(oCanvas);
// point in YZ coordinates
BSMath.DoubleXY p = new BSMath.DoubleXY();
p.X = (oCanvas.OriginY - v.Y) / oCanvas.ZoomFactor;
p.Y = (oCanvas.OriginX - v.X) / oCanvas.ZoomFactor;
#endregion
#region 2. Update cursor and info
if (oSettings.ShowInformation)
{
_info.Info = p.X.ToString("0.0") + " | " + p.Y.ToString("0.0");
_info.Render(0, 0);
_info.Visual.Offset = v;
}
// move cursor
_cursor.Visual.Offset = v;
}
Using the mousemove event seems to be creating a lot of overhead and I can see that there are issues tracking the mouse movements when I move the mouse quickly.
Can anyone recommend a better way of creating the same effect?
example http://www.iccg.be/test/images/canvas.jpg
Edit:
I investigated it a bit further and the problem seems to occur when the resolution of the canvas is bigger. If it is a 600x400 canvas then there is no delay, but when it is around 1000x800 I get the problem with delays when hoovering. The performance also improves if I use user drawn crosshairs instead of the lines that have the full width/ height of the canvas.
I recently have built something similar and haven't had any performance issues.
Did it the very simple way by adding the stuff directly on the canvas.
The drawn items are in a second canvas behind the mouse position canvas. Both reside in a Grid.
This is for sure not the most sophisticated way to solve this, but it works quite well for me.
Here's the code:
private Point _previous;
private Point _current;
private Line _xLine;
private Line _yLine;
private TextBlock _displayTextBlock;
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
_current = e.GetPosition(myCanvas);
if (_previous != _current)
{
if (_xLine == null)
{
_xLine = new Line() {X1 = 0, X2 = myCanvas.ActualWidth, Stroke = new SolidColorBrush(Colors.Black)};
_yLine = new Line() {Y1 = 0, Y2 = myCanvas.ActualHeight, Stroke = new SolidColorBrush(Colors.Black)};
_displayTextBlock = new TextBlock();
myCanvas.Children.Add(_xLine);
myCanvas.Children.Add(_yLine);
myCanvas.Children.Add(_displayTextBlock);
}
_displayTextBlock.SetValue(Canvas.TopProperty, _current.Y);
_displayTextBlock.SetValue(Canvas.LeftProperty, _current.X);
_displayTextBlock.Text = _current.X.ToString() + " | " + _current.Y.ToString();
_xLine.Y1 = _current.Y;
_xLine.Y2 = _current.Y;
_yLine.X1 = _current.X;
_yLine.X2 = _current.X;
_previous = _current;
}
}

Categories

Resources