图片的旋转
知识点
Matrix:旋转对象
Reset:重载
createBitmap:创建位图
//代码示例
package com.example.examples_05_08;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
public class GameView extends View implements Runnable {
Bitmap qQBit;
int bitWidth;
int bitHeight;
float Angle=0.0f;//旋转角度
Matrix matrix=new Matrix();//设置旋转
public GameView(Context context) {
super(context);
// TODO Auto-generated constructor stub
//装载图片
qQBit=((BitmapDrawable)getResources().getDrawable(R.drawable.qq)).getBitmap();
bitHeight=qQBit.getHeight();
bitWidth=qQBit.getWidth();
new Thread(this).start();
}
public void run() {
// TODO Auto-generated method stub
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
Thread.currentThread().interrupt();
}
postInvalidate();
}
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
//设置背景颜色
canvas.drawColor(Color.BLACK);
matrix.reset();//重载图片
//设置旋转角度
matrix.setRotate(Angle);
//按matrix的旋转构建新的Bitmap:参数1:位图,参数2:x,参数3:y,参数4:宽度,参数5:高,参数6:旋转,参数7:滤镜
Bitmap bitmap=Bitmap.createBitmap(qQBit, 0, 0, bitWidth, bitHeight,matrix,true);
//绘制
GameView.drawImage(canvas, bitmap, (320-bitWidth)/2, 10);
}
/**
* 绘制一个bitmap
* @param bitmap图片
* @param x 屏幕x坐标
* @param y 屏幕y坐标
* */
public static void drawImage(Canvas canvas,Bitmap bitmap,int x,int y) {
canvas.drawBitmap(bitmap, x,y,null);
}
}
package com.example.examples_05_08;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
public class MainActivity extends Activity {
GameView gameView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView=new GameView(this);
setContentView(gameView);
}
public boolean onKeyDown(int keyCode,KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT)
{
gameView.Angle--;
}
else if (keyCode==KeyEvent.KEYCODE_DPAD_RIGHT) {
gameView.Angle++;
}
return true;
}
}