【发布时间】:2020-10-08 08:28:05
【问题描述】:
我在屏幕上有一个图像视图,我想制作一个动画以将其移动到该屏幕的中心。我只是不知道如何计算或获得该中心。图片不在上/下/左/右。
谢谢!
【问题讨论】:
-
粘贴处理此问题的代码部分将帮助其他人知道要提供哪些帮助。
标签: android xml kotlin animation
我在屏幕上有一个图像视图,我想制作一个动画以将其移动到该屏幕的中心。我只是不知道如何计算或获得该中心。图片不在上/下/左/右。
谢谢!
【问题讨论】:
标签: android xml kotlin animation
使用 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"/>
【讨论】:
这里是可以帮助你的代码。
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);
【讨论】: