用户界面之view(视图)

Focus on technology, enjoy life!—— QQ:804212028 浏览链接:

主题:用户界面之view(视图) -View类是Android的一个超类,这个类几乎包含了所有的屏幕类型。每一个View都有一个用于绘图的画布,这个画布可以进行任意扩展。在游戏开发中叶可以自定义视图(View),这个画布的功能更能满足我们在游戏开发中的需要。在Android中,任何一个View类都只需重写onDraw方法来实现界面显示,自定义的视图可以是复杂的3D实现,,也可以是非常简单的文本形式等。

View使用实例 让我们来自定义一个GameView视图(用来显示游戏界面),一切自定义视图都来自View,所以它必须继承父类View。

GameView.java的源代码:

import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.view.View;{int miCount = 0;public GameView(Context context) {super(context);}(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((320 – 80) / 2, 0, (320 – 80) / 2 + 80, 40, mPaint);}}

MainActivity.java源代码:

import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.KeyEvent;import android.view.MotionEvent;{private GameView mGameView = null;(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// 实例化GameView对象 this.mGameView = new GameView(this);// 设置显示为我们自定义的View(GameView)setContentView(mGameView);// 开启线程new Thread(new GameThread()).start();}Handler myHandler = new Handler() {(Message msg) {switch (msg.what) {case 1:// 注意这里的刷新界面实际上是在UI线程中执行的 不是另外开启一个线程,这里要搞清楚//invalidate()是用来刷新View的,必须是在UI线程中进行工作mGameView.invalidate();break;}super.handleMessage(msg);}};class GameThread implements Runnable {() {while (!Thread.currentThread().isInterrupted()) {Message message = new Message();message.what = 1;// 发送消息myHandler.sendMessage(message);try {Thread.sleep(1000);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}}}}

运行结果:

矩形颜色会不断的刷新变化,模拟了刷新游戏界面的效果。

Focus on technology, enjoy life!—— QQ:804212028 浏览链接:

往事是尘封在记忆中的梦,而你是我唯一鲜明的记忆,

用户界面之view(视图)

相关文章:

你感兴趣的文章:

标签云: