将动画翻译到屏幕中心

时间:2020-10-08 08:28:05

标签: android xml kotlin animation

我在屏幕上有一个图像视图,我想制作一个动画以将其移动到该屏幕的中央。我只是不知道如何计算或获得该中心。图片不在顶部/底部/左侧/右侧。

谢谢!

2 个答案:

答案 0 :(得分:0)

使用pivotX 50%和pivotY 50%,它将缩放到中心:

   <scale
    android:fromXScale="1.0"
    android:toXScale="1.2"
    android:fromYScale="1.0"
    android:toYScale="1.2"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="175"/>

答案 1 :(得分:0)

这是可以帮助您的代码。

void moveToCenterAnimation(Context context, View view, long duration) {

    //Get position on screen
    int[] pos = new int[2];
    view.getLocationOnScreen(pos);

    //Get screen size
    int screenWidth, screenHeight;
    screenWidth = context.getResources().getDisplayMetrics().widthPixels;
    screenHeight = context.getResources().getDisplayMetrics().heightPixels;

    //x and y translate animators
    ObjectAnimator xAnimator = ObjectAnimator.ofFloat(view, "translationX", screenWidth/2f - pos[0] + view.getWidth()/2f);
    ObjectAnimator yAnimator = ObjectAnimator.ofFloat(view, "translationY", screenHeight/2f - pos[1] + view.getHeight()/2f);
    xAnimator.setDuration(duration);
    yAnimator.setDuration(duration);
    
    //Play animator
    AnimatorSet animatorSet = new AnimatorSet();
    animatorSet.playTogether(xAnimator, yAnimator);
    animatorSet.start();
}

//Then use this function to animate view
moveToCenterAnimation(getContext(), yourImageView, 300);