Volodymyr Dovhopoliuk
Volodymyr Dovhopoliuk

Reputation: 13

Apply multiple RenderTransforms to UIElements

I'm creating Path objects with curvy edges on a Canvas. I want to be able to rotate them and move them around the canvas. But when I try to apply several transform to and object it only visually displays the last one. I assume its because the transforms are applied to the coordinates of the Path object and are only displayed but not saved afterwards.

So if I would run something like:

my_canvas.Children[0].RenderTransform = new TranslateTransform(0, 100);
my_canvas.Children[0].RenderTransform = new TranslateTransform(0, 150);

it would move my Path 150 pixels down.

Is there a way i can save the transform progress of RenderTransform or do i have to recreate my Path with different parameters/write a method to displace the pixels manually?

Edit

Another example:

my_canvas.Children[0].MouseDown += (object sender, MouseButtonEventArgs e) => 
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    MouseDownLocation = e.GetPosition(my_canvas);
                }
            };

            my_canvas.Children[0].MouseMove += (object sender, MouseEventArgs e) =>
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                {                    
                    my_canvas.Children[0].RenderTransform  = new TranslateTransform(-(MouseDownLocation.X - e.GetPosition(my_canvas).X), -(MouseDownLocation.Y - e.GetPosition(my_canvas).Y));                    
                }
            };

This code allows me to move my element and it works fine: I can pick it up, visually move it, and let it go. But only once. If try to do it again it tries to do the transformation based on the elements' previous position. And as I am typing this I realize that I can probably solve this by keeping track of the offsets the transformations are causing.

Upvotes: 1

Views: 741

Answers (1)

Clemens
Clemens

Reputation: 128157

Just add the next translation to the X and Y values of the existing RenderTransform:

my_canvas.Children[0].RenderTransform = new TranslateTransform(0, 100);
((TranslateTransform)my_canvas.Children[0].RenderTransform).Y += 150;

Or use Canvas.Left and Canvas.Top instead of a TranslateTransform:

UIElement element = my_canvas.Children[0];
Canvas.SetTop(element, 100);
Canvas.SetTop(element, Canvas.GetTop(element) + 150);

Upvotes: 1

Related Questions