关闭

android游戏开发初学之SurfaceView绘制界面

标签: androidandroid游戏
126人阅读 评论(0) 收藏 举报
分类:

绘制界面需要先锁定一个画布,创建画笔,绘制完成之后需要解锁画布并提交

package com.learn.swl.game;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Created by ADM on 2015/11/17.
 */
public class GameUi extends SurfaceView implements SurfaceHolder.Callback,Runnable{
    private boolean threadFlag;
    private  SurfaceHolder holder;
    private  Canvas canvas;
    public GameUi(Context context) {
        super(context);
        holder = getHolder();
        holder.addCallback(this);
    }
    private void DrawUI(){
        try {
            canvas = holder.lockCanvas();//锁定画布
            if(canvas!=null){
                Paint paint = new Paint();//创建画笔
                paint.setColor(Color.RED);//设置画笔颜色
                canvas.drawRect(0, 0, 100, 100, paint);//画一个矩形
            }
        }catch (Exception e){

        }finally {
            if(canvas!=null){
                holder.unlockCanvasAndPost(canvas);//解锁并提交画布
            }
        }

    }
    @Override
    public void run() {
        while (threadFlag){
            DrawUI();
        }
    }
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        System.out.println("surfaceCreated");
        Thread thread = new Thread(this);
        threadFlag = true;//线程开启标志
        thread.start();//线程开启
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        System.out.println("surfaceChanged");

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        System.out.println("surfaceDestroyed");
        threadFlag = false;
    }


}

在这里用到threadFlag来控制线程的销毁,以及防止重复创建线程

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2075次
    • 积分:55
    • 等级:
    • 排名:千里之外
    • 原创:3篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档