最近准备研究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)
andsurfaceDestroyed(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