view

原创
2015/07/02 13:10
阅读数 5
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();
            }
        }
    };
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部