view

Activity
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

/**
 * @version 2012-8-9 下午03:36:51 使用view刷新頻率高的話會有閃屏
 **/
public class Gameview extends View {
    int miCount = 0;
    int x = 0, y = 0;

    public Gameview(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if(miCount < 100) {
            miCount++;
        }
        else {
            miCount = 0;
        }
        // 設置畫筆
        Paint mpaint = new Paint();
        switch(miCount % 4) {
            case 0:
                mpaint.setColor(Color.BLUE);
                break;
            case 1:
                mpaint.setColor(Color.GREEN);
                break;
            case 2:
                mpaint.setColor(Color.RED);
                break;
            case 3:
                mpaint.setColor(Color.YELLOW);
                break;
            default:
                mpaint.setColor(Color.WHITE);
                break;
        }
        // 畫實心矩形
        canvas.drawRect(x, y, x + 100, y + 100, mpaint);
    }
}
VIEW
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class main extends Activity {
    Gameview mGameview;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGameview = new Gameview(this);
        setContentView(mGameview);
        new Thread(new GameThread()).start();
    }

    Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // 刷新view 從新執行 onDraw
            // mGameview.invalidate();
        }
    };

    class GameThread implements Runnable {

        @Override
        public void run() {
            // 若是當前線程中斷返回true
            while(!Thread.currentThread().isInterrupted()) {
                try {
                    Message msg = mhandler.obtainMessage();
                    msg.sendToTarget();
                    Thread.sleep(100);
                }
                catch(Exception e) {
                    Thread.currentThread().interrupt();
                }
                // 也可不使用Handler直接刷新view
                mGameview.postInvalidate();
            }
        }
    };
}


版權聲明:本文爲博主原創文章,未經博主容許不得轉載。java

相關文章
相關標籤/搜索