androidanimationmatrixandroid-canvasandroid-animation

in android canvas why the matrix is too slow and sluggish


I wanted to rotate image in android app around the center pivot and following is the code..

package com.android.maddy.canvs;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;

import android.os.Handler;
import android.provider.OpenableColumns;
import android.view.MotionEvent;
import android.view.View;

public class drawview extends View {
    private Drawable d[]=new Drawable[2];

    Boolean done=false;
    Handler h;
    float th=0;
    public drawview(Context context) {
        super(context);
        d[0]=context.getResources().getDrawable(R.drawable.appdatabk);
        d[1]=context.getResources().getDrawable(R.drawable.appdata);
        h = new Handler();
    }

    Runnable r =new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub

            th++;
            invalidate();
        }
    };

    public void onDraw(Canvas c){
        super.onDraw(c);
        Paint p =new Paint();
        Rect imageBounds = c.getClipBounds();  // for the background
        d[0].setBounds(imageBounds);

        d[0].draw(c);

        Matrix m = new Matrix();
        m.setTranslate(getWidth()/2, getHeight()/2);        
        m.preRotate(th,43,160); //my image is 86x320

        Bitmap b =     BitmapFactory.decodeResource(getResources(),R.drawable.appdata);//image of the bottle i want to rotate
        c.drawBitmap(b,m, p);
        p.setColor(Color.BLUE);
        h.postDelayed(r,1);


    }



    }

What happens here is that the matrix calculation slows down the speed of rotation and thus it gives ugly sluggish output.. If you have another method to rotate the image around center pivot without using matrix or there is some other method then Please help me out.. I also removed the matrix and checked the rotation in drawBitmap() function using x+r*(Math.cos(th)) and y+r*(Math.sin(th)) that works fine but image doesn't rotate around pivot.. Please help.. Thanks


Solution

  • Matrix is quite fast. What is slowing you down is that you create classes and load bitmaps in the onDraw. Create the Paint and the Matrix one in the class, and also load the bitmap once