Android学习笔记——图像旋转实例

package com.test.view;

import com.test.R;
import Android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.view.KeyEvent;
import android.view.View;

/**
* @author Administrator
*
*/
public class GameView extends View implements Runnable {

Bitmap qqmap = null;
int qq_width = 0;
int qq_height = 0;
float Angle = 0.0f;

Matrix m = new Matrix();

/**
* @param context
*/
public GameView(Context context) {
   super(context);
   // TODO Auto-generated constructor stub
   qqmap = ((BitmapDrawable)this.getResources().getDrawable(R.drawable.qq)).getBitmap();
   qq_width = qqmap.getWidth();
   qq_height = qqmap.getHeight();
 
   new Thread(this).start();
 
}

public void onDraw(Canvas canvas)
{
   super.onDraw(canvas);
 
   m.reset();
 
   m.setRotate(Angle);
 
   Bitmap qq2 = Bitmap.createBitmap(qqmap,0,0,qq_width,qq_height,m,true);
 
   GameView.drawImage(canvas,qq2,(320-qq_width)/2,10);
 
   qq2 = null;
 
}

public boolean onKeyDown(int keyCode,KeyEvent event)
{
   if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT)
   {
    Angle--;
   }
   else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT)
   {
    Angle++;
   }
   return true;
}

/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
   // TODO Auto-generated method stub
   while (!Thread.currentThread().isInterrupted())
   {
    try
    {
     Thread.sleep(100);
    }
    catch (InterruptedException e)
    {
     Thread.currentThread().interrupt();
    }
    postInvalidate();
   }

}

public static void drawImage(Canvas canvas,Bitmap bitmap,int x,int y)
{
   canvas.drawBitmap(bitmap,x,y,null);
}

}

 

package com.test;

import com.test.view.GameView;
import android.app.Activity;
import android.os.Bundle;

public class TestAndroid extends Activity {

private GameView gv = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        this.gv = new GameView(this);
        setContentView(gv);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
       if (gv == null) {
           return false;
       }
       return gv.onKeyDown(keyCode, event);
   }
}

相关推荐