安卓通过SurfaceView类实现手写功能(中)

2.2 创建SurfaceView控件对应的变量

首先,为MainActivity定义SurfaceView类的对象

private SurfaceView surfViewDraw=null;

之后在MainActivity类的onCreate()方法中将该对象与控件关联

surfViewDraw=(SurfaceView)findViewById(R.id.surfVDraw);

2.3 获取SurfaceHolder

通过SurfaceView类的getHolder()方法获取其对应的SurfaceHolder接口。

首先,为MainActivity定义SurfaceHolder接口的对象

private SurfaceHolder surHolder=null;

之后在MainActivity类的onCreate()方法中获取SurfaceViewSurfaceHolder接口:

surHolder=surfViewDraw.getHolder();

其中,surfViewDraw是在“2.2 创建SurfaceView控件对应的变量”中获取的SurfaceView控件的对象。

2.4 添加回调接口

通过SurfaceHolder接口的addCallback()方法为SurfaceHolder添加回调接口。

2.4.1 addCallback()方法

该方法的格式为

void addCallback(SurfaceHolder.Callback callback)

其中,参数是SurfaceHolder.Callback接口。通过实现该接口可以接收Surface发生改变的信息。实现SurfaceHolder.Callback接口必须要重写该接口的三个方法,即surfaceCreated()surfaceChanged()surfaceDestroyed()

MainActivity类的onCreate()方法中添加如下代码

surHolder.addCallback(new SurfaceHolder.Callback(){
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
    {   
    }
    public void surfaceCreated(SurfaceHolder holder)
    {     
    }
    public void surfaceDestroyed(SurfaceHolder holder)
    {        
    }
});

2.4.2 surfaceChanged()方法

Surface上发生改变时,该方法会被调用,可以在该方法中更新Surface的图像。从图2中可以看出,SurfaceView控件的背景是黑色,该方法的主要功能就是通过位图(Bitmap)初始化SurfaceView控件背景的画布(Canvas)。

surfaceChanged()方法的格式为

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

int height)

其中,holder表示发生改变的SurfaceHolderformat表示Surface的像素格式;widthheight分别表示Surface的宽度和高度。

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
    if(mBitmap==null) {
        
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);         

        mCanvas.drawBitmap(mBitmap, 0, 0, null);
    }
}

通过Bitmap类的createBitmap创建与Surface相同大小的位图;之后通过Canvas类的构造函数将画布mCanvas与位图mBitmap关联起来;最后,通过drawBitmap()方法画出位图。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值