Android 原生层SurfaceView截屏

背景:flutter嵌入原生view时,原生view使用的surfaveview,导致下面两种方法无法正常使用。

  1. 导致flutter无法通过id找到RenderRepaintBoundarytoImage来抓取widget
  2. 原生层无法通过view去获取Bitmap

方案:使用PixelCopy方法抓取屏幕像素数据,并且复制到Bitmap

java 复制代码
import android.os.Looper;
import android.graphics.Bitmap;
import android.view.PixelCopy;
import android.view.SurfaceView;
import java.io.ByteArrayOutputStream;

// surfaceView 为所需要截图的组件

private void getSurfaceViewBitmap() {
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
	    int width = surfaceView.getWidth();
	    int height = surfaceView.getHeight();
	    final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
	    PixelCopy.request(surfaceView, bitmap, copyResult -> {
	        if (copyResult == PixelCopy.SUCCESS) {
	            ByteArrayOutputStream stream = new ByteArrayOutputStream();
	            // 此处为了flutter层使用,实际纯原生可以不做这个转换
	            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
	            byte[] imageInByte = stream.toByteArray();
	            HashMap<String, Object> map = new HashMap<>();
	            map.put("bytes", imageInByte);
	            Log.d("jingluo", "success")
	        } else {
	            Log.d("jingluo", "failed")
	        }
	    }, new Handler(Looper.getMainLooper()));
	}
}
相关推荐
安卓开发者10 小时前
Android RxJava 组合操作符实战:优雅处理多数据源
android·rxjava
阿华的代码王国10 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
一条上岸小咸鱼10 小时前
Kotlin 基本数据类型(三):Booleans、Characters
android·前端·kotlin
Jerry说前后端10 小时前
RecyclerView 性能优化:从原理到实践的深度优化方案
android·前端·性能优化
alexhilton11 小时前
深入浅出着色器:极坐标系与炫酷环形进度条
android·kotlin·android jetpack
一条上岸小咸鱼17 小时前
Kotlin 基本数据类型(一):Numbers
android·前端·kotlin
Huntto17 小时前
最小二乘法计算触摸事件速度
android·最小二乘法·触摸事件·速度估计
一笑的小酒馆18 小时前
Android中使用Compose实现各种样式Dialog
android
红橙Darren18 小时前
手写操作系统 - 编译链接与运行
android·ios·客户端
鹏多多.21 小时前
flutter-使用device_info_plus获取手机设备信息完整指南
android·前端·flutter·ios·数据分析·前端框架