Android - 将 imageView 发送到 X Y 位置

Android - Send imageView to X Y position

我有一个从右侧屏幕开始的 imageView A。 我想以编程方式设置 X 和 Y 位置。要将 imageView 移动到左上角附近,我必须设置 X = -1497 Y = 20。我不明白的是为什么 X = -1497。我想是因为它占据了 imageView 开始的 (0,0) 位置,但是如何在左上角的屏幕上捕捉 (0,0)?

这是因为,对于所有屏幕,我必须计算一个 % 以始终将 imageView 移动到同一个位置,但是如何使用负值来做到这一点。

Point origImagePos = new Point(-1460, 20);

public void moveImageView(View view){
  ObjectAnimator objectX;
  ObjectAnimator objectY;
  AnimatorSet animatorXY;

  objectX = ObjectAnimator.offFloat(view, "translationX", origImagePos.x);
  objectY = ObjectAnimator.offFloat(view, "translationY", origImagePos.y);
  animatorXY.playTogether(objectX, objectY);
  animatorXY.setDuration(500);
  animatorXY.start();
}

问候

translationX 相对于视图起作用。试试这个,

objectX = ObjectAnimator.offFloat(view, "X", 20);
objectY = ObjectAnimator.offFloat(view, "Y", 20);

实际上,您可以使用 ViewPropertyAnimator 而不是 ObjectAnimator 来削减大部分代码。

public void moveImageView(View view){

    view.animate().translationX(0).translationY(0).setDuration(500);

}

这就是您需要的所有代码,应该将视图移至左上角。

您总是可以为以后的动画增强您的方法,例如:

// You should also always use Interpolators for more realistic motion.

public void moveImageView(View view, float toX, float toY, int duration){

     view.animate()
        .setInterpolator(new AccelerateDecelerateInterpolator())
        .translationX(toX)
        .translationY(toY)
        .setDuration(duration);
}

然后像这样称呼它:

moveImageView(yourImageView, 0, 0, 500);

动态获取设备坐标,以便您知道移动到哪里:

float screenWidth = getResources().getDisplayMetrics().widthPixels;
float screenHeight = getResources().getDisplayMetrics().heightPixels;

screenWidth + screenHeight 就是右下角的坐标

左上角坐标就是 0, 0。

屏幕中心坐标在逻辑上是 (screenWidth / 2) + (screenHeight / 2)。

希望这能让你以后的生活更轻松。