Android:如何在动画中保持宽高比

10
我正在一个ImageView内运行的动画,但它不会保持图像帧的纵横比。以下SO答案相当详细,但似乎对我不起作用: 如何在ImageView中缩放图像以保持纵横比
这里是代码:
private void startAnimation(){
    mImageView.setAdjustViewBounds(true);
    mImageView.setScaleType(ScaleType.CENTER);
    mImageView.setBackgroundResource(R.anim.my_animation);

    AnimationDrawable frameAnimation = (AnimationDrawable) mImageView.getBackground();

     // Start the animation (looped playback by default).
     frameAnimation.start();
}

R.anim.my_animation只是一个动画列表:

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/selected"
android:oneshot="false">
<item
    android:drawable="@drawable/photo_1"
    android:duration="100" />
<item
    android:drawable="@drawable/photo__2"
    android:duration="100" />
    ... and so on...
</animation-list>

1
根据您提到的问题,解决方案在于 XML 布局。请发表您的 XML 布局,以便我们确认您是否正确定义了参数。 - user432209
@user432209:+1。你帮我找出了错误。我将ImageView的高度和宽度设置为绝对值(因为它显示除动画之外的一些内容)。删除这些设置解决了问题。谢谢! - OceanBlue
2个回答

13

不要将动画drawable设置为ImageView的背景,而是使用src将其设置为前景,并在那里播放动画。如果为ImageView设置合适的比例类型,则帧动画中的所有图像都将保持纵横比缩放。

    private void startAnimation(){
    mImageView.setAdjustViewBounds(true);
    mImageView.setScaleType(ScaleType.CENTER);
    mImageView.setImageDrawable(getResources().getDrawable(R.anim.my_animation)); 

    AnimationDrawable frameAnimation = (AnimationDrawable) mImageView.getDrawable();

     // Start the animation (looped playback by default).
     frameAnimation.start();
}

我为你解决我的问题而点赞了你的回答。请注意,你只能使用mImageView.setImageResource(R.anim.my_animation)这个简短的代码。 - Jeff T.
谢谢,这个技巧对矢量图像也适用!! - Bruce

0

这有点棘手,但它可以正常工作。我在我的动画列表中有两张图片。

<animation-list xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/selected" android:oneshot="false">
    <item android:drawable="@drawable/logo1" android:duration="5000" />
    <item android:drawable="@drawable/logo2" android:duration="300" />
</animation-list>

然后我添加了第三张图片(logo0),它与logo1/2的大小相同,但是它完全透明。 最后我使用了这个ImageView:

<ImageView
    android:id="@+id/imageViewLogo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:adjustViewBounds="true"
    android:layout_margin="5dp"
    android:src="@drawable/logo0"
/>

现在我的动画保持了图片标志的纵横比。

代码如下:

    @Override
    public void onCreate(Bundle savedInstanceState) {
    ...
    imageView = (ImageView) findViewById(R.id.imageViewLogo);
    imageView.setBackgroundResource(R.drawable.logo_animation);
    ...


    public void onWindowFocusChanged (boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
     AnimationDrawable frameAnimation = (AnimationDrawable) imageView.getBackground();
     if(hasFocus) { frameAnimation.start(); } else { frameAnimation.stop(); }
    }

这非常简单,只需要在您的资源中添加一些虚拟图片即可,无需额外的代码,也不需要复杂的计算。


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