android中SurfaceView的简单介绍

本文介绍在Android中如何使用SurfaceView来处理需要大量刷新和自定义绘图的应用场景。提供了SurfaceView的基本使用模板,并解释了其生命周期回调方法surfaceCreated、surfaceChanged和surfaceDestroyed的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么时候使用SurfaceView?

当 自定义的View 需要频繁更新,刷新的数据量 大的时候,SurfaceView是通过子线程来进行刷新的。

SurfaceView如何使用?

SurfaceView在 使用时,有一套可供参考的模板,大部分的SurfaceView绘图操作都可套用这个模板。

public class MySurfaceView extends SurfaceView
        implements SurfaceHolder.Callback, Runnable {

    private SurfaceHolder holder;
    private boolean isDrawing;
    private Canvas canvas;

    public MySurfaceView(Context context) {
        this(context, null);
    }

    public MySurfaceView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MySurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    //初始化
    private void init() {
        holder = getHolder();
        holder.addCallback(this);
        holder.setFormat(PixelFormat.RGB_565);
        //
        setFocusable(true);
        setFocusableInTouchMode(true);
        setKeepScreenOn(true);
    }

    //绘制
    private void draw() {
        canvas = holder.lockCanvas();
        //进行 绘制
        //todo
        if (canvas != null) {
            holder.unlockCanvasAndPost(canvas);
        }
    }

    //---------------
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isDrawing = true;
        //启动 子线程
        new Thread(this).start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder,
                               int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isDrawing = false;
    }

    @Override
    public void run() {
        while (isDrawing) {
            draw();
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值