package com.example.examples_05_07;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
public class GameView extends View implements Runnable {
Bitmap mBitQQ;//聲明一個位圖
Bitmap mBitDestTop;//聲明一個位圖
int miDTX=0;
public GameView(Context context) {
super(context);
// TODO Auto-generated constructor stub
miDTX=0;
/*從資源文件轉載圖片*/
//getResources()->獲得Resources
//getDrawable()->獲得資源中的Drawable對象,參數爲資源索引ID
//getBitmap()->獲得Bitmap
//獲得位圖,將獲得的圖片存儲在位圖中
mBitQQ=((BitmapDrawable)getResources().getDrawable(R.drawable.qq)).getBitmap();
mBitDestTop=((BitmapDrawable)getResources().getDrawable(R.drawable.desktop)).getBitmap();
//開啓線程
new Thread(this).start();
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
//清屏效果
canvas.drawColor(Color.BLACK);
//在屏幕0,0處繪製該圖像
GameView.drawImage(canvas, mBitQQ, 0, 0);
/*在指定位置區域進行裁剪*/
//getWidth()->獲得圖片的寬度
//getHeight()->獲得圖片的高度
GameView.drawImage(canvas, mBitDestTop, miDTX, mBitQQ.getHeight(), mBitDestTop.getWidth(), mBitDestTop.getHeight()/2,
0, 0);
}
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();
}
}
/**--------------------------------------
* 繪製圖片
* @param x:屏幕x座標
* @param y:屏幕y座標
* @param w:要繪製圖片的寬度
* @param h:要繪製圖片的高度
* @param bx:圖片上的x座標
* @param by:圖片上的y座標
* */
public static void drawImage(Canvas canvas,Bitmap bitmap,int x,int y,int w,int h,int bx,int by) {
Rect src=new Rect();//圖片裁剪區域
Rect dest=new Rect();//屏幕裁剪區域
//設置圖片裁剪區域
src.left=bx;
src.top=by;
src.right=bx+w;
src.bottom=by+h;
//設置屏幕裁剪區域
dest.left=x;
dest.top=y;
dest.right=x+w;
dest.bottom=y+h;
//繪製圖片
canvas.drawBitmap(bitmap, src, dest, null);
src=null;
dest=null;
}
/**
* 繪製一個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_07;
import android.os.Bundle;
import android.R.integer;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
public class MainActivity extends Activity {
GameView mgameView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mgameView=new GameView(this);
setContentView(mgameView);
}
public boolean onKeyDown(int keyCode,KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT)
{
if(mgameView.miDTX>0)
{
mgameView.miDTX--;
}
}
else if (keyCode==KeyEvent.KEYCODE_DPAD_RIGHT) {
if(mgameView.miDTX+mgameView.mBitDestTop.getWidth()<320)
{
mgameView.miDTX+=10;
}
}
return true;
}
//觸筆事件
public boolean onTouchEvent(MotionEvent event) {
return true;
}
}