WPF.以编程方式将图像移动到(X,Y)的最简单方法? [英] WPF. Easiest way to move Image to (X,Y) programmatically?

查看:18
本文介绍了WPF.以编程方式将图像移动到(X,Y)的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道一种简单的方法,可以使用没有 XAML 的 WPF 动画 100% 以编程方式将图像从当前位置移动到新位置 (X,Y) 的动画?并且没有提及this"(使用 RegisterName 等).

Does anyone know of an easy way to animate a movement from an Image's current location to a new location (X,Y) using WPF animation with no XAML, 100% programmatically? And with no reference to "this" (with RegisterName etc).

我正在尝试为 Image 制作一个扩展类,以在其上执行动画操作.通过动画改变宽度和高度属性很容易,但在搜索对象的位置动画后,它突然变得更高级.

I am trying to make an extension class for Image to do animation stuff on it. It is easy enough to change the width and height properties through animation, but after searching for location animation of an object it suddenly becomes more advanced.

因为它是一个扩展类,所以我只会引用实际的 Image 对象以及我想要将它移动到的 X 和 Y.

As it is an extension class I will only have a reference to the actual Image object and the X and Y I want to move it to.

public static void MoveTo(this Image targetControl, double X, double Y, double Width, double Height){
 //code here
 ...
}

更新:

谢谢.快工作了.似乎 GetTop 和 GetLeft 返回未明确设置的NaN".在这篇文章中找到了解决方法:Canvas.GetTop() 返回 NaN

Thanks. Almost working. It seems The GetTop and GetLeft returns 'NaN' not explicitly set. Found the workaround in this post: Canvas.GetTop() returning NaN

public static void MoveTo(this Image target, double newX, double newY) {
                Vector offset = VisualTreeHelper.GetOffset(target);
                var top = offset.Y;
                var left = offset.X;
                TranslateTransform trans = new TranslateTransform();
                target.RenderTransform = trans;
                DoubleAnimation anim1 = new DoubleAnimation(0, newY - top, TimeSpan.FromSeconds(10));
                DoubleAnimation anim2 = new DoubleAnimation(0, newX - left, TimeSpan.FromSeconds(10));
                trans.BeginAnimation(TranslateTransform.YProperty, anim1);
                trans.BeginAnimation(TranslateTransform.XProperty, anim2);
        }

我不得不用 0 交换两个值 (FROM).我认为这一定是因为在这种情况下图片的左上角是原点?但现在它起作用了.

I had to swap two of the values (FROM) with 0. I assume that must be because in this context the upper left corner of the picture is the origin? But now it works.

推荐答案

试试这个:

public static void MoveTo(this Image target, double newX, double newY)
{
    var top = Canvas.GetTop(target);
    var left = Canvas.GetLeft(target);
    TranslateTransform trans = new TranslateTransform();
    target.RenderTransform = trans;
    DoubleAnimation anim1 = new DoubleAnimation(top, newY - top, TimeSpan.FromSeconds(10));
    DoubleAnimation anim2 = new DoubleAnimation(left, newX - left, TimeSpan.FromSeconds(10));
    trans.BeginAnimation(TranslateTransform.XProperty,anim1);
    trans.BeginAnimation(TranslateTransform.YProperty,anim2);
}

这篇关于WPF.以编程方式将图像移动到(X,Y)的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆