Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to maintain aspect-ratio in animation

The animation I am running inside an imageview refuses to maintain the aspect-ratio of the image frames. The following answers in SO are quite informative, but don't seem to work for me: How to scale an Image in ImageView to keep the aspect ratio

Here is the code:

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 is just an animation list:

<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>
like image 396
OceanBlue Avatar asked Feb 02 '23 18:02

OceanBlue


1 Answers

Instead of setting the animation drawable in the background of the imageview, set it in the foreground using src and let the animation play there. All images in the frame animation will be resized with aspect ratio intact provided you set a suitable scale type for the 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();
}
like image 100
A.J. Avatar answered Feb 12 '23 05:02

A.J.