Android图形系统之Surface、SurfaceView、SurfaceHolder及SurfaceHolder.Callback之间的联系

本文深入解析了Android中的SurfaceView及其相关组件,包括Surface、SurfaceHolder和SurfaceHolder.Callback等核心概念。详细介绍了它们之间的交互方式和工作原理,以及如何利用SurfaceView进行高效的屏幕绘制。

/********************************************************************************************
* author:conowen@大钟
* E-mail:conowen@hotmail.com
* http://blog.youkuaiyun.com/conowen
* 注:本文为原创,仅作为学习交流使用,转载请标明作者及出处。

********************************************************************************************/


1、Surface


Surface

extends Object
implements Parcelable
java.lang.Object
android.view.Surface

Class Overview


Handle onto a raw buffer that is being managed by the screen compositor.

简单翻译:

Surface是原始图像缓冲区(raw buffer)的一个句柄,而原始图像缓冲区是由屏幕图像合成器(screen compositor)管理的。




1.1、 就如在C语言编程一样,通过一个文件的句柄,就可以操作文件,获取文件的内容。 同样的,通过Surface就可以获取raw buffer其中的内容。原生缓冲区(raw buffer)存储着当前窗口的像素数据。


1.2、事实上,当得到一个Surface对象时,同时会得到一个Canvas(画布)对象。这一点可以通过查看\frameworks\base\core\java\android\view\Surface.java文件可知道Surface类定义了一个Canvas成员变量


    //@\frameworks\base\core\java\android\view\Surface.java
    // The mSurfaceControl will only be present for Surfaces used by the window
    // server or system processes. When this class is parceled we defer to the
    // mSurfaceControl to do the parceling. Otherwise we parcel the
    // mNativeSurface.
    private int mSurfaceControl;
    private int mSaveCount;
    private Canvas mCanvas;
    private int mNativeSurface;
    private int mSurfaceGenerationId;
    private String mName;

1.3、 理解Canvas对象,可以把它当做画布,Canvas的方法大多数是设置画布的大小、形状、画布背景颜色等等,要想在画布上面画画,一般要与Paint对象结合使用,顾名思义,Paint就是画笔的风格,颜料的色彩之类的。

        // 创建画笔  
        Paint paint = new Paint();  
        paint.setColor(Color.RED);// 设置红色  

        canvas.drawCircle(60, 20, 10, paint);// 画一个圆  


1.4、Surface本身的作用类似一个句柄,得到了这个句柄就可以得到其中的Canvas、原生缓冲器以及其它方面的内容。


1.5、Surface实现了Parcelable接口,(implements Parcelable),也就是说Surface对象可以把显示内容的数据写入到 Parcel 中,并且能够从Parcel读回数据。

Parcelable

android.os.Parcelable
Known Indirect Subclasses

Class Overview


Interface for classes whose instances can be written to and restored from a Parcel. Classes implementing the Parcelable interface must also have a static field calledCREATOR, which is an object implementing theParcelable.Creator interface.

简单翻译:
实现这个接口的对象可以写入数据到Parcel,同时也可以把数据读出来。



2、SurfaceView


SurfaceView

extends View
java.lang.Object
android.view.View
android.view.SurfaceView
Known Direct Subclasses

Class Overview


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.

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

The Surface will be created for you while the SurfaceView's window is visible; you should implementsurfaceCreated(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:

简单翻译:

SurfaceView提供了一个专门用于绘制的surface,这个surface内嵌于。你可以控制这个Surface的格式和尺寸。Surfaceview控制这个Surface在屏幕的正确绘制位置。

surface是Z-ordered的(也就是说在xyz坐标系中,按照Z坐标排序的,Z值大的表面覆盖在Z值小的表面的上方),这表明它总在自己所在窗口的后面。surfaceview在显示窗口处为Surface提供了一个可见区域,通过这个区域,才能看到Surface里面的内容。可以放置一些覆盖图层(overlays)在Surface上面,如Button、Textview之类的。但是,需要注意的是,如果Surface上面有全透明的控件,那么随着Surface的每一次变化,这些全透明的控件就会重新渲染,这样的话,就影响性能与显示的效果。

你可以通过SurfaceHolder这个接口去访问Surface,而执行getHolder()方法可以得到SurfaceHolder接口。

当SurfaceView的窗口可见时,Surface就会被创建,当SurfaceView窗口隐藏时,Surface就会被销毁。当然了,你也可以通过复写surfaceCreated(SurfaceHolder)surfaceDestroyed(SurfaceHolder) 这两个方法来验证一下Surface何时被创建与何时被销毁。

SurfaceView提供了一个运行在渲染线程的surface,若你要更新屏幕,你需要了解以下线程知识。


2.1、SurfaceView与Surface的联系

简单来说,SurfaceView与Surface的联系就是,Surface是管理显示内容的数据(implementsParcelable),包括存储于数据的交换。而SurfaceView就是把这些数据显示出来到屏幕上面。

两者联系如图所示:



3、SurfaceHolder


SurfaceHolder

android.view.SurfaceHolder

Class Overview


Abstract interface to someone holding a display surface. Allows you to control the surface size and format, edit the pixels in the surface, and monitor changes to the surface. This interface is typically available through theSurfaceView class.

When using this interface from a thread other than the one running its SurfaceView, you will want to carefully read the methodslockCanvas() andCallback.surfaceCreated().

简单翻译:

SurfaceHolder是控制surface的一个抽象接口,你可以通过SurfaceHolder来控制surface的尺寸和格式,或者修改surface的像素,监视surface的变化等等,SurfaceHolder是SurfaceView的典型接口。

与直接控制SurfaceView来修改surface不同,使用SurfaceHolder来修改surface时,需要注意lockCanvas()Callback.surfaceCreated().这两个方法。

SurfaceHolder控制surface的流程所使用的几个方法。

3.1、abstract void addCallback(SurfaceHolder.Callback callback)
Add a Callback interface for this holder.// 给SurfaceHolder一个回调对象。

3.2、abstract Canvas lockCanvas(Rect dirty)
Just like lockCanvas() but allows specification of a dirty rectangle.
// 锁定画布中的某一个区域,返回的画布对象Canvas(当更新的内容只有一个区域时,同时要追求高效,可以只更
新一部分的区域,而不必更新全部画布区域)

3.3、abstract Canvas lockCanvas()
Start editing the pixels in the surface.// 锁定画布,返回的画布对象Canvas

3.4、abstract void removeCallback(SurfaceHolder.Callback callback)
Removes a previously added Callback interface from this holder.//移除回调对象

3.5、abstract void unlockCanvasAndPost(Canvas canvas)
Finish editing pixels in the surface.// 结束锁定画图,并提交改变。

4、SurfaceHolder.Callback

SurfaceHolder.Callback

android.view.SurfaceHolder.Callback
Known Indirect Subclasses

Class Overview


A client may implement this interface to receive information about changes to the surface. When used with aSurfaceView, the Surface being held is only available between calls tosurfaceCreated(SurfaceHolder) andsurfaceDestroyed(SurfaceHolder). The Callback is set withSurfaceHolder.addCallback method.

简单翻译:

SurfaceHolder.Callback是监听surface改变的一个接口

4.1、public abstract voidsurfaceChanged(SurfaceHolder holder, int format, int width, int height)
holderThe SurfaceHolder whose surface has changed.
formatThe new PixelFormat of the surface.
widthThe new width of the surface.
heightThe new height of the surfa
//surface发生改变时被调用


4.2、public abstract voidsurfaceCreated(SurfaceHolder holder)

Parameters
holderThe SurfaceHolder whose surface is being created

//在surface创建时被调用,一般在这个方法里面开启渲染屏幕的线程。


4.3、public abstract voidsurfaceDestroyed(SurfaceHolder holder)
Parameters
holderThe SurfaceHolder whose surface is being destroyed.
//销毁时被调用,一般在这个方法里将渲染的线程停止。


附上上述所说几种的联系方法

SurfaceHolder = SurfaceView.getHolder();

Surface = SurfaceHolder.getSurface();

Canvas =SurfaceHolder.LockCanvas(Rect dirty)

Canvas   =Surface.lockCanvas(Rect dirty)


5、Demo小程序

共有两个class效果图如下,具体看代码和注释。


进入程序,执行

public void surfaceCreated(SurfaceHolder holder)

然后执行

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

退出程序调用surfaceDestroyed,释放资源。

public void surfaceDestroyed(SurfaceHolder holder)




/****************************************************************/

效果图:


@MySurfaceView.java

/*
 * author: conowen
 * e-mail: conowen@hotmail.com
 * date  :  2012.8.4
 */
package com.conowen.SurfaceViewDemo;

import android.app.Activity;
import android.os.Bundle;

public class SurfaceViewDemoActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.main);
        setContentView(new MySurfaceView(this));
        
    }
}



@SurfaceViewDemoActivity.java

/*
 * author: conowen
 * e-mail: conowen@hotmail.com
 * date  :  2012.8.4
 */
package com.conowen.SurfaceViewDemo;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MySurfaceView extends SurfaceView implements
		SurfaceHolder.Callback {

	private String TAG = "conowen";
	
	private SurfaceHolder sfh;
	private boolean ThreadFlag;
	private int counter;
	private Canvas canvas;

	private Thread mThread = new Thread(new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (ThreadFlag) {

				// 锁定画布,得到Canvas对象
				canvas = sfh.lockCanvas();

				// 设定Canvas对象的背景颜色
				canvas.drawColor(Color.GREEN);

				// 创建画笔
				Paint p = new Paint();
				// 设置画笔颜色
				p.setColor(Color.RED);
				// 设置文字大小
				p.setTextSize(40);

				// 创建一个Rect对象rect
				// public Rect (int left, int top, int right, int bottom)
				Rect rect = new Rect(100, 50, 400, 350);
				// 在canvas上绘制rect
				canvas.drawRect(rect, p);
				// 在canvas上显示时间
				// public void drawText (String text, float x, float y, Paint
				// paint)
				canvas.drawText("时间 = " + (counter++) + " 秒", 500, 200, p);

				if (canvas != null) {
					// 解除锁定,并提交修改内容,更新屏幕
					sfh.unlockCanvasAndPost(canvas);
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	});

	public MySurfaceView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub

		// 通过SurfaceView获得SurfaceHolder对象
		sfh = this.getHolder();

		// 为SurfaceHolder添加回调结构SurfaceHolder.Callback
		sfh.addCallback(this);

	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
		Log.i(TAG, "surfaceChanged");

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		Log.i(TAG, "surfaceCreated");
		counter = 0;
		ThreadFlag = true;
		mThread.start();

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		Log.i(TAG, "surfaceDestroyed");
		ThreadFlag = false;

	}

}




### ### SurfaceHolder.Callback 接口的作用和使用方法 在 Android 开发中,`SurfaceHolder.Callback` 是一个用于监听 `SurfaceView` 中 `Surface` 生命周期变化的接口。它允许开发者在 `Surface` 被创建、改变大小或销毁时执行特定的操作,从而确保与 `Surface` 相关的资源能够被正确地初始化、调整或释放。 该接口定义了三个必须实现的方法: - `surfaceCreated(SurfaceHolder holder)`:当 `Surface` 被成功创建时调用。此方法通常用于初始化与 `Surface` 相关的资源,例如启动视频播放或相机预览[^1]。 - `surfaceChanged(SurfaceHolder holder, int format, int width, int height)`:当 `Surface` 的尺寸或格式发生变化时调用。通常用于调整渲染内容的大小或重新配置渲染参数[^1]。 - `surfaceDestroyed(SurfaceHolder holder)`:当 `Surface` 被销毁时调用。此方法通常用于释放占用的资源,如停止播放器、关闭相机等[^1]。 为了将 `SurfaceHolder.Callback` 与 `SurfaceView` 关联,需要通过 `SurfaceHolder.addCallback()` 方法注册回调。该回调机制确保了开发者能够在合适的时机执行与 `Surface` 生命周期相关的操作。 以下是一个典型的使用示例: ```java public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback { private SurfaceHolder surfaceHolder; public MySurfaceView(Context context) { super(context); surfaceHolder = getHolder(); surfaceHolder.addCallback(this); } @Override public void surfaceCreated(SurfaceHolder holder) { // 在此处启动视频播放或相机预览 } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // 在此处调整视频或相机的显示尺寸 } @Override public void surfaceDestroyed(SurfaceHolder holder) { // 在此处释放资源,如停止播放器或关闭相机 } } ``` 通过实现 `SurfaceHolder.Callback` 接口并将其添加到 `SurfaceHolder` 中,开发者可以有效地管理 `SurfaceView` 的生命周期事件,从而实现更稳定和可控的图形渲染流程。 --- ### ### 注意事项 - `SurfaceHolder.Callback` 的回调方法只在 `Surface` 的生命周期内有效,即从 `surfaceCreated()` 到 `surfaceDestroyed()` 之间。因此,任何依赖 `Surface` 的操作都应在这两个回调之间执行[^1]。 - 如果需要更复杂的生命周期控制,可以使用 `SurfaceHolder.Callback2`,它是 `SurfaceHolder.Callback` 的扩展版本,支持更细粒度的控制[^3]。 - 在多线程环境中操作 `Surface` 时,应确保线程安全,尤其是在执行绘图或视频解码等任务时。 --- ### ### 相关问题 1. 如何在 Android 中使用 SurfaceHolder.Callback 实现视频播放? 2. SurfaceHolder.CallbackSurfaceHolder.Callback2 的区别是什么? 3.SurfaceHolder.CallbacksurfaceDestroyed 方法中应该释放哪些资源? 4. 为什么在使用 SurfaceHolder.Callback 时需要在构造函数中调用 addCallback? 5. SurfaceView 和 TextureView 在处理 Surface 生命周期时有何不同?
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值