android基础之SurfaceView视图中对画布的3种刷新方法

//MysurfaceView.java

创新互联坚持“要么做到,要么别承诺”的工作理念,服务领域包括:网站设计制作、成都做网站、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的泉山网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!

package com.example.surfaceview;

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;

public class MysurfaceView extends SurfaceView implements Callback{

private SurfaceHolder sfh;

private Paint paint;

private int textX=10,textY=10;

public MysurfaceView(Context context)

{

super(context);

sfh=this.getHolder();//控制SurfaceView的大小 格式 主要用于监听SurfaceView的状态

//其实surfaceView只是保存当前视图的像素数据 在使用surfaceView时  并不会与surfaceview直接打交道

//而是通过surfaceHolder来控制 使用surfaceHolder的lockCanvas()函数获取到surfaceView的

//canvas对象 。在通过在canvas上绘制内容来修改surfaceView中的数据

//locakCanvas不仅获取canvas  还对获取的canvas进行加锁

sfh.addCallback(this);//将其监听接口实例传入..完成对surfaceView的监听

paint=new Paint();

paint.setColor(Color.WHITE);

setFocusable(true);

}

@Override

public void surfaceChanged(SurfaceHolder holder, int format, int width,

int height) {

// TODO Auto-generated method stub

}

@Override

public void surfaceCreated(SurfaceHolder holder) {

// TODO Auto-generated method stub

myDraw();

}

@Override

public void surfaceDestroyed(SurfaceHolder holder) {

// TODO Auto-generated method stub

}

public void myDraw()

{

Canvas canvas=sfh.lockCanvas();

canvas.drawRect(0, 0,this.getWidth(),this.getHeight(),paint);//the first method 绘制一个和手机屏幕一样大小的矩形

canvas.drawColor(Color.BLACK);//the second methos绘制颜色填充整个屏幕

canvas.drawRGB(0,0,0);//the third method 绘制颜色填充整个屏幕 

canvas.drawText("game", textX, textY, paint);

sfh.unlockCanvasAndPost(canvas);

}

public boolean onTouchEvent(MotionEvent event)

{

textX=(int)event.getX();

textY=(int)event.getY();

myDraw();

invalidate();

return true;

}

}

//MainActivity.java如下:

package com.example.surfaceview;

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(new MysurfaceView(this));

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

}


分享标题:android基础之SurfaceView视图中对画布的3种刷新方法
网站链接:http://ybzwz.com/article/gggdps.html