How can I allow the size of an ImageView to vary with an AnimationDrawable?

I plan to animate an explosion with an AnimationDrawable and I have frames saved of increasing sizes:

enter image description here

The problem is that I specify the ImageView size initially to wrap_content, so when I play the animation, the ImageView's size remains constant and the larger frames just skew down to match the original size.

How can I allow the ImageView to increase in size as the image increases while being animated?

1 answer

  • answered 2018-01-13 18:31 0X0nosugar

    You can set any View's width and height by assigning LayoutParams with the desired width/ height to that View. You can use e.g. a ValueAnimator and ValueAnimator.AnimatorUpdateListener to get something like an impulse generator and modify and re-set the LayoutParams repeatedly.

    BUT in my opinion that's not the best way to go, and so I won't give the full particulars of this approach. Why do I think it is bad? Because by repeatedly changing the View's boundaries you will cause at least the whole ViewGroup containing the View to go through a new layout pass every time you change the boundaries. This may be no problem on many devices, but all device owners will benefit from apps which don't unnecessarily drain the battery.

    My suggestion is to use an ImageView which has the size of the biggest frame you wish to show. By keeping this ImageView's size unchanged we enable the runtime to "concentrate" on re-drawing just the area covered by the ImageView, which will be much better for performance.

    By setting the attribute android:scaleType="center" you will cause all frames to appear centered (and not scaled) in the ImageView, so I think this will give the desired effect.

    If on the other hand your ImageView is not the only thing which has to be moved/ changed then I'd look into the Transition framework.