Search code examples
androidanimationsmoothing

Stuttering Animation


I wrote an application which has an Image which fit to the whole screen. The Image.resource is a png with the size 768x1024 pixel.

<ImageView
    android:id="@+id/imgage1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="fitXY"
    android:src="@drawable/imagepng" />

The code to animate this Imageview is as follows:

public void animate(int percent) {
    height = imgage1.getMeasuredHeight()/100;
    ObjectAnimator anim = ObjectAnimator.ofFloat(ActivityMain.this.imgage1, "translationY",ActivityMain.this.imgage1.getTranslationY(), - (percent*height));
    ObjectAnimator.setFrameDelay(24);
    anim.setDuration(5000);
    anim.setInterpolator(new AccelerateDecelerateInterpolator());
    anim.start();
    }

unfortunately the animation stutters. I thought this stuttering comes from the scaletype "fitXY" because on every animationstepp the Imageview scales the png. What can I do if I want to use fitXY with one PNG for all Windowsizes to eleminate the stuttering


Solution

  • Meanwhile I have found the reason why the animation is stuttering:

    Because the scaletype of the Imageview is set to fitXY, the system renders on each frame a new scaled bitmap, that costs much performance. So I dont attach the Bitmap by XML to the Imageview,. This work is done by a ncustom ImageView-Class:

    public class CustomImageView extends ImageView {
    Bitmap bitmapScaled;
    Bitmap bitmapOrg;
    public CustomImageView (Context context,AttributeSet attr) {
        super(context,attr);
        Resources mRes = context.getResources();
        bitmapOrg = BitmapFactory.decodeResource(mRes, R.drawable.thepng);
        }
    @Override
    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);
        canvas.drawBitmap(bitmapScaled,0, 0, null);
        }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if(bitmapScaled == null)    {
            bitmapScaled = Bitmap.createScaledBitmap(bitmapOrg,getMeasuredWidth(),getMeasuredHeight(),true);
            }
        }
    }