最近看了很多项目代码都使用了SurfaceView,因为想要显示图片,一般是使用ImageView,但看到有些使用SurfaceView,查了资料,以下是一些差别,ImageView主要是显示单张图片,而如果是显示动画,摄像头,逐帧显示视频,则使用SurfaceView,相关的代码有以下:
导入使用import android.view.SurfaceView (不是android.view.Surface)
SurfaceView.getHolder()
SurfaceHolder.addCallback(callback)
SurfaceHolder.lockCanvas()
SurfaceHolder是一个接口,它的实例对象可以这样获取,
surfaceHolder = surfaceView.getHolder();
SurfaceHolder有个CallBack成员,也是接口,包含三个成员方法
void surfaceCreated(@NonNull SurfaceHolder holder);
void surfaceChanged(@NonNull SurfaceHolder holder, @PixelFormat.Format int format,
@IntRange(from = 0) int width, @IntRange(from = 0) int height);
void surfaceDestroyed(@NonNull SurfaceHolder holder);
刚上面提到Surface,SurfaceView的源码,可以看到里面定义了一个Surface成员变量
public class SurfaceView extends View implements ViewRootImpl.SurfaceChangedCallback {
private static final String TAG = "SurfaceView";
private static final boolean DEBUG = false;
private static final boolean DEBUG_POSITION = false;
@UnsupportedAppUsage
final ArrayList<SurfaceHolder.Callback> mCallbacks = new ArrayList<>();
final int[] mLocation = new int[2];
@UnsupportedAppUsage
final ReentrantLock mSurfaceLock = new ReentrantLock();
@UnsupportedAppUsage
final Surface mSurface = new Surface(); // Current surface in use