10

我在 imageview 中运行的动画拒绝保持图像帧的纵横比。SO中的以下答案非常有用,但似乎对我不起作用: How to scale an Image in ImageView to keep the aspect ratio

这是代码:

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>
4

2 回答 2

12

与其在 imageview 的背景中设置可绘制动画,不如使用 src 将其设置在前台并让动画在那里播放。如果您为图像视图设置了合适的比例类型,则帧动画中的所有图像都将按照完整的纵横比调整大小。

    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();
}
于 2013-12-24T18:43:33.080 回答
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(); }
    }

它非常简单,只需要额外的虚拟图片资源:没有额外的代码,没有复杂的计算。

于 2013-03-11T22:00:06.327 回答