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

101

我有一个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中,但我尝试了其他布局也没有变化。

4个回答

175

50% 是动画视图的中心。

50%p 是父容器的中心。

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

30
对我来说,50%的工作已经完成了(不含P)。 - agamov
5
如果与您应用动画的组件宽度或高度有关,则应省略“p”字母。这里的“p”指的是您应用动画的组件的父级组件。请注意不改变原意,使翻译更加易懂。 - Alan Deep
如何在Java文件中使用50%p,而不是XML? - Nikola K.
8
新的比例动画:new ScaleAnimation(1.0f, 1.2f, 1.0f, 1.2f, Animation.RELATIVE_TO_PARENT, 0.5f, Animation.RELATIVE_TO_PARENT, 0.5f)。该动画将以相对于父视图的0.5倍为基准,使视图的大小从1.0倍增加到1.2倍。 - Jiang Qi
还有一个设置像素的 "a" - Animation.ABSOLUTE。 - Zon

127

@stevanveltema和@JiangQi提供的答案很完美,但如果你想要使用代码进行缩放,那么你可以使用我的答案。

// 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);

1
@T.Todua 什么错误?请提出一个新问题并链接回这个答案。 - Rohan Kandwal
如果我想要无限重复动画怎么办,例如:android:repeatCount="infinite" android:repeatMode="reverse" - Ali Tamoor

78

忘记额外的翻译,将android:pivotXandroid:pivotY设置为宽度和高度的一半,它将从图像中心进行缩放。


3
pivotXpivotY 应该设置为视口宽度和高度的一半,以达到精确的效果。 - Etienne Lawlor

7
您可以在集合中使用平移动画来实现此功能。您可能需要调整toXDelta和toYDelta值以使其保持图像居中。
<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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接