Android 遊戲開發之View框架

MainActivity.java
 
[java] 
package com.soai.view; 
 
import android.os.Bundle; 
import android.app.Activity; 
import android.view.Window; 
import android.view.WindowManager; 
 
public class MainActivity extends Activity { 
 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        //全屏顯示 
        this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
        setContentView(new MyView(this)); 
    } 
}   www.aiwalls.com

MyView.java
 
[java] 
package com.soai.view; 
 
import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.view.MotionEvent; 
import android.view.View; 
 
/**
 * 
 * @author SoAi
 *
 */ 
public class MyView extends View { 
    private int textX = 20,textY = 20; 
     
    public MyView(Context context) { 
        super(context); 
        setFocusable(true); 
    } 
     
    @Override 
    protected void onDraw(Canvas canvas) { 
        //創建一個畫筆實例 
        Paint paint = new Paint(); 
        paint.setColor(Color.RED); 
        //繪制文本 
        canvas.drawText("Game", textX, textY, paint); 
        super.onDraw(canvas); 
    } 
     
    @Override 
    public boolean onTouchEvent(MotionEvent event) { 
        //獲取用戶觸屏的X軸賦值給文本的X坐標 
        textX = (int)event.getX(); 
        //獲取用戶觸屏的Y軸賦值給文本的Y坐標 
        textY = (int)event.getY(); 
        invalidate();    
        return true; 
    } 
 

 
MyView需要繼承View,實現裡面的onDraw(Canvas canvas)方法,Canvas為畫佈類相當於一張白紙,而Paint為畫筆類恰好是畫圖工具的筆,利用這兩個類可以很好的實現遊戲中的繪圖。
調用invalidate()方法 則重新繪圖一下,也就是調用onDraw()方法一次。如果在其它類中調用,則需要調用postInvalidate();這個方法。

You May Also Like