SurfaceView的经典写法
来源:互联网 发布:外国人在淘宝买东西吗 编辑:程序博客网 时间:2024/06/05 06:58
package com.example.test;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.view.MotionEvent;import android.view.SurfaceHolder;import android.view.SurfaceHolder.Callback;import android.view.SurfaceView;/** * 继承SurfaceView * 实现SurfaceHolder.Callback,给SurfaceHolder用的 * 创建SurfaceHolder,并addCallback,SurfaceView的一切都有SurfaceHolder控制 */public class MySurfaceView extends SurfaceView implements Callback, Runnable {//SurfaceView基本private SurfaceHolder sfh;//操控SurfaceViewprivate Paint p;private Canvas c;//线程private Thread t;private boolean flag;//数据private int screenW, screenH;private int xx = 100, yy = 100;public MySurfaceView(Context context) {super(context);sfh = this.getHolder();sfh.addCallback(this);p = new Paint();p.setColor(Color.RED);}@Overridepublic boolean onTouchEvent(MotionEvent event) {xx = (int) event.getX();yy = (int) event.getY();return true;}public void myDraw() {try {//当SurfaceView不可编辑或尚未创建,会返回nullc = sfh.lockCanvas();if(c != null) {c.drawColor(Color.GREEN);//刷屏c.drawText("me", xx, yy, p);//画}} catch(Exception e) {} finally {if(c != null) {sfh.unlockCanvasAndPost(c);}}}//游戏逻辑public void logic() {}@Overridepublic void surfaceCreated(SurfaceHolder holder) {screenW = this.getWidth();screenH = this.getHeight();//线程的初始化和启动都写在create里面flag = true;t = new Thread(this);t.start();}@Overridepublic void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {}@Overridepublic void surfaceDestroyed(SurfaceHolder holder) {flag = false;}@Overridepublic void run() {while (flag) {//刷屏时间保持一致//一般会在10~20帧左右//每秒20帧:1000ms/20=50ms每帧long start = System.currentTimeMillis();myDraw();logic();long end = System.currentTimeMillis();try {if(end - start < 50) {Thread.sleep(50 - (end-start));}} catch (InterruptedException e) {e.printStackTrace();}}}}
SurfaceView的生命周期:
2 1
- SurfaceView的经典写法
- SurfaceView的标准写法
- <学习记录>记录自定义SurfaceView的一般写法
- 经典写法
- js插件的经典写法与总结
- js插件的经典写法与总结
- js插件的经典写法与总结
- 【SurfaceView】SurfaceView的初步学习
- Android的Listview的ListAdapter关于View的经典写法
- 一道经典的sql面试题不同的写法
- mysql经典语句写法
- SWing的经典写法,了解事件驱动和内部类
- javascript js表示中文日期的经典写法
- mvc三层架构中经典的CRUD写法(1)
- RecyclerView多布局写法,“我的”、“个人中心” 页面经典写法演示
- SurfaceView--扩展SurfaceView的基础模版代码
- android的surfaceView介绍
- SurfaceView的学习
- ThinkPHP3.2.2学习记录
- java.sql.SQLException: ORA-00911: invalid character 解决方法(转)
- 确保对象的唯一性——单例模式
- 初识Spring配置,看代码遇到的问题.
- 延迟加载的单例设计模式
- SurfaceView的经典写法
- Objective-C NSString和NSMutableString
- HTML5 09 圆角和阴影
- 机房收费系统之报表
- java远程debug
- indy和socket的一些区别
- CGI介绍
- 我做的一个web项目从tomcat迁移到weblogic遇到的问题
- yum命令详解