序章
TextureView は SurfaceView に似ており、ビデオまたは OpenGL シーンの表示に使用できます。
SurfaceView との違い
SurfaceView では変形や拡大縮小などの操作ができず、2 つの SurfaceView を重ね合わせる(オーバーレイ)こともできません。
TextureView は別のウィンドウを作成せず、通常の View として機能します。この機能により、TextureView の移動、変形、アニメーション化などが可能になります。たとえば、透明度を設定できます。
TextureView は、ハードウェア アクセラレーションされたウィンドウでのみ使用できます。ソフトウェアでレンダリングする場合、TextureView は何も描画しません。
TextureViewはSurfaceViewよりも多くのメモリを消費しますので、使用する際は選択に注意してください。
使用
TextureView の使用は簡単です。必要なのは、SurfaceTexture を取得することだけです。次に、SurfaceTexture を使用してコンテンツを表示します。以下は、TextureView を使用してカメラのプレビュー インターフェイスを表示する方法を示しています。
まずハードウェア アクセラレーションを有効にします。
<activity android:name=".activity.TextureActivity"
android:hardwareAccelerated="true"></activity>
class TextureActivity : AppCompatActivity(),TextureView.SurfaceTextureListener {
private var camera : Camera? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_texture)
tv_video.surfaceTextureListener = this
}
override fun onSurfaceTextureAvailable(surface: SurfaceTexture?, width: Int, height: Int) {
//在SurfaceTexture可用时调用
camera = Camera.open()//打开相机
try{
//设置相机预览的容器
camera?.setPreviewTexture(tv_video.surfaceTexture)
camera?.setDisplayOrientation(90)
//开始预览
camera?.startPreview()
}catch (e:Exception){
}
}
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture?, width: Int, height: Int) {
//当SurfaceTexture缓冲区大小更改时调用
}
override fun onSurfaceTextureUpdated(surface: SurfaceTexture?) {
//当SurfaceTexture有更新时调用
}
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture?): Boolean {
//当指定SurfaceTexture即将被销毁时调用。
//如果返回true,则调用此方法后,表面纹理中不会发生渲染。
//如果返回false,则客户端需要调用SurfaceTexture#release()。大多数应用程序应该返回true
camera?.stopPreview()
camera?.release()
return true
}
}
TextureView の使用について知っておくべき最も重要なことは、SurfaceTexture は TextureView がウィンドウにアタッチされた後 (そして onAttachedToWindow() が呼び出された後) にのみ使用できるということです。したがって、SurfaceTexture が使用可能なときに関連する操作を実行することをお勧めします。
TextureView を使用できるのは 1 人の呼び出し元だけであることに注意してください。たとえば、TextureView を使用してカメラ プレビューを表示している場合、TextureView での描画中に lockCanvas() を使用することはできません。