SurfaceView + SurfaceHolder 入门

本文介绍了Android中SurfaceView和SurfaceHolder的使用,包括它们在UI线程和渲染线程中的作用,如何创建SurfaceUI类,实现SurfaceHolder.Callback接口,以及在合适的时间调用渲染线程进行界面绘制。通过示例展示了如何在surfaceCreated和surfaceDestroyed之间启动和停止渲染线程,以及如何使用lockCanvas和unlockCanvasAndPost方法进行界面更新。
摘要由CSDN通过智能技术生成

最近准备研究cocos2d,所以先记录下SurfaceView学习笔记。


先看看官方API文档对SurfaceView的描述:
https://developer.android.com/reference/android/view/SurfaceView.html

Provides a dedicated drawing surface embedded inside of a view hierarchy. You can control the format of this surface and, if you like, its size; the SurfaceView takes care of placing the surface at the correct location on the screen

The surface is Z ordered so that it is behind the window holding its SurfaceView; the SurfaceView punches a hole in its window to allow its surface to be displayed. The view hierarchy will take care of correctly compositing with the Surface any siblings of the SurfaceView that would normally appear on top of it. This can be used to place overlays such as buttons on top of the Surface, though note however that it can have an impact on performance since a full alpha-blended composite will be performed each time the Surface changes.

The transparent region that makes the surface visible is based on the layout positions in the view hierarchy. If the post-layout transform properties are used to draw a sibling view on top of the SurfaceView, the view may not be properly composited with the surface.

Access to the underlying surface is provided via the SurfaceHolder interface, which can be retrieved by calling getHolder().

The Surface will be created for you while the SurfaceView’s window is visible; you should implement surfaceCreated(SurfaceHolder) and surfaceDestroyed(SurfaceHolder) to discover when the Surface is created and destroyed as the window is shown and hidden.

One of the purposes of this class is to provide a surface in which a secondary thread can render into the screen. If you are going to use it this way, you need to be aware of some threading semantics:

All SurfaceView and SurfaceHolder.Callback methods will be called from the thread running the SurfaceView’s window (typically the main thread of the application). They thus need to correctly synchronize with any state that is also touched by the drawing thread.

You must ensure that the drawing thread only touches the underlying Surface while it is valid – between
SurfaceHolder.Callback.surfaceCreated() and
SurfaceHolder.Callback.surfaceDestroyed().

由于全段过长,我只加粗了重点部分。
简单来说,要使用SurfaceView,需要两个线程:

  • 主线程(即UI线程):用于接受用户操作输入
  • 第二线程(secondary thread):用于渲染界面

那么我们首先创建一个SurfaceUI类(extends SurfaceView)作为界面。

public class SurfaceUI extends SurfaceView{
   

    public SurfaceUI(Context context) {
        super
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值