在TextureView上显示一张图片
时间: 2023-12-10 12:42:28 浏览: 360
要在 `TextureView` 上显示一张图片,可以按照以下步骤进行:
1. 将图片转换成 `Bitmap` 对象。可以使用 `BitmapFactory` 类中的 `decodeResource()` 方法将资源文件中的图片转换为 `Bitmap` 对象,如下所示:
```java
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
```
2. 获取 `TextureView` 对象,并设置 `SurfaceTextureListener` 监听器。在监听器的 `onSurfaceTextureAvailable()` 方法中可以获取 `SurfaceTexture` 对象,并将 `Bitmap` 绘制到 `SurfaceTexture` 中。
```java
TextureView textureView = findViewById(R.id.texture_view);
textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
// 将 Bitmap 绘制到 SurfaceTexture 中
Canvas canvas = surfaceTexture.lockCanvas();
canvas.drawBitmap(bitmap, 0, 0, null);
surfaceTexture.unlockCanvasAndPost(canvas);
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {}
});
```
3. 最后,在布局文件中添加 `TextureView` 控件即可。
```xml
<TextureView
android:id="@+id/texture_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
完整示例代码如下:
```java
public class MainActivity extends AppCompatActivity {
private Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 将图片转换为 Bitmap 对象
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_image);
// 获取 TextureView 对象,并设置 SurfaceTextureListener 监听器
TextureView textureView = findViewById(R.id.texture_view);
textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
// 将 Bitmap 绘制到 SurfaceTexture 中
Canvas canvas = surfaceTexture.lockCanvas();
canvas.drawBitmap(bitmap, 0, 0, null);
surfaceTexture.unlockCanvasAndPost(canvas);
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {}
});
}
}
```
布局文件:
```xml
<TextureView
android:id="@+id/texture_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
阅读全文