Android‎ > ‎

Rotate Canvas With Finger

posted Feb 27, 2013, 11:15 PM by Akash Khaitan   [ updated Mar 9, 2013, 7:47 AM ]
Suppose a canvas is to be rotated with the finger, along the specified point

In ActionDown
Take the points, and hence we have a line1


In ActionMove
Take the points, and we get line 2

Find the angle between the lines, and call invalidate

In OnDraw
Rotate the canvas as per the angle


Check RotateView class below


public class RotateView extends ImageView {

    double angle1,angle;
    float x,y;
    Bitmap bm;
    public RotateView(Context context, AttributeSet attrs) {
        super(context, attrs);
        bm=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        if(event.getAction()==MotionEvent.ACTION_DOWN)
        {
            x=event.getX();
            y=event.getY();
            angle1=Math.atan2(y-50, x-50);
           
        }
        if(event.getAction()==MotionEvent.ACTION_MOVE)
        {
            double angle2=Math.atan2(event.getY()-50, event.getX()-50);
           
            angle=Math.toDegrees(angle2-angle1);
            Log.w("angle1",Double.toString(angle1));
            Log.w("angle2",Double.toString(angle2));
            Log.w("Angle",Double.toString(angle));
           
            invalidate();
           
        }
        return true;
    }
   
    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        canvas.translate(50, 50);
//    canvas.drawColor(Color.RED);
        canvas.rotate((int)angle, 0, 0);
        canvas.drawBitmap(bm, 0, 0, null);
        super.onDraw(canvas);
    }
}


Comments