相对于中心点的 Android 图像缩放动画

我有一个 ImageView,我做了一个简单的缩放动画。非常标准的代码。

我的 scale _ up. xml:

<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale android:fromXScale="1"
android:fromYScale="1"
android:toXScale="1.2"
android:toYScale="1.2"
android:duration="175"/>
</set>

我的动画代码:

Animation a = AnimationUtils.loadAnimation(this, R.anim.scale_up);
((ImageView) findViewById(R.id.circle_image)).startAnimation(a);

问题是:

当图像缩放时,它不是从中心缩放,而是从左上角缩放。换句话说,缩放版本的图像不具有与中心相同的点,但它具有相同的左上角点。 下面这张图解释了我的意思:

How the animation scales How I want it

第一个图像是动画如何缩放,第二个图像是我希望它如何缩放。它应该保持中心点不变。 我试过在图像上、容器上设置重力,左右对齐,总是相同的比例。

我在主屏幕上使用 RelativeLayout,而 ImageView 位于另一个 RelativeLayout 中,但我尝试了其他布局,没有改变。

93969 次浏览

You can use the translate animation in your set to offset that. You'll probably need to tweak the toXDelta and toYDelta values to get it right so it keeps the image centered.

<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale android:fromXScale="1"
android:fromYScale="1"
android:toXScale="1.2"
android:toYScale="1.2"
android:duration="175"/>
<translate
android:fromXDelta="0"
android:fromYDelta="0"
android:toXDelta="-20%"
android:toYDelta="-20%"
android:duration="175"/>
</set>

Forget the additional translation, set android:pivotX, android:pivotY to half the width and height and it will scale from the center of the image.

50% is center of animated view.

50%p is center of parent

<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"/>

The answer provided by @stevanveltema and @JiangQi are perfect but if you want scaling using code, then you can use my answer.

// first 0f, 1f mean scaling from X-axis to X-axis, meaning scaling from 0-100%
// first 0f, 1f mean scaling from Y-axis to Y-axis, meaning scaling from 0-100%
// The two 0.5f mean animation will start from 50% of X-axis & 50% of Y-axis, i.e. from center


ScaleAnimation fade_in =  new ScaleAnimation(0f, 1f, 0f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
fade_in.setDuration(1000);     // animation duration in milliseconds
fade_in.setFillAfter(true);    // If fillAfter is true, the transformation that this animation performed will persist when it is finished.
view.startAnimation(fade_in);