问题描述
我在执行翻译动画的 ImageView 中有一个子弹图像.
I have an image of a bullet in an ImageView that does Translate animation.
我需要显示实时坐标以实时显示它与目标的距离.
I need to show real time coordinates to show how far it is from target in real time.
ImageView myimage = (ImageView)findViewById(R.id.myimage);
Animation animation = new TranslateAnimation(100, 200, 300, 400);
animation.setDuration(1000);
myimage.startAnimation(animation);
animation.setRepeatCount(Animation.INFINITE);
是否可以在执行 TranslateAnimation 时获取图像的实时 x 和 y 坐标?
Is it possible to get real time x and y coordinates of the image while it is doing TranslateAnimation ?
如果不能使用 TranslateAnimation,有没有其他方法可以在运动时提供图像的实时坐标?
And if its not possible using TranslateAnimation, is there any other way that gives real time coordinates of image while in motion ?
我试过了-
int x = myimage.getLeft();
int y = myimage.getTop();
和
int[] firstPosition = new int[2];
myimage.measure(View.MeasureSpec.EXACTLY, View.MeasureSpec.EXACTLY);
myimage.getLocationOnScreen(firstPosition);
int x = firstPosition[0];
int y = firstPosition[1];
但在这两种方式中,它都给出了 ImageView 的初始静态坐标.
but in both the ways, its giving the initial static coordinate of the ImageView.
推荐答案
下面是一个基于 user3249477 和 Vikram 所说的完整示例:
Here's a complete example based on what user3249477 and Vikram said:
final TextView positionTextView = (TextView)findViewById(R.id.positionTextView);
ImageView myimage = (ImageView)findViewById(R.id.imageView);
ObjectAnimator translateXAnimation= ObjectAnimator.ofFloat(myimage, "translationX", 0f, 100f);
ObjectAnimator translateYAnimation= ObjectAnimator.ofFloat(myimage, "translationY", 0f, 100f);
translateXAnimation.setRepeatCount(ValueAnimator.INFINITE);
translateYAnimation.setRepeatCount(ValueAnimator.INFINITE);
AnimatorSet set = new AnimatorSet();
set.setDuration(1000);
set.playTogether(translateXAnimation, translateYAnimation);
set.start();
translateXAnimation.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
imageXPosition = (Float)animation.getAnimatedValue();
}
});
translateYAnimation.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
imageYPosition = (Float)animation.getAnimatedValue();
String position = String.format("X:%d Y:%d", (int)imageXPosition, (int)imageYPosition);
positionTextView.setText(position);
}
});
这篇关于是否可以在翻译动画中获取 ImageView 的实时坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!