Android 遊戲開發之View架構

來源:互聯網
上載者:User

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.2cto.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();這個方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.