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()));
	}
}
相关推荐
robotx27 分钟前
安卓线程相关
android
消失的旧时光-19431 小时前
Android 面试高频:JSON 文件、大数据存储与断电安全(从原理到工程实践)
android·面试·json
dalancon2 小时前
VSYNC 信号流程分析 (Android 14)
android
dalancon2 小时前
VSYNC 信号完整流程2
android
dalancon2 小时前
SurfaceFlinger 上帧后 releaseBuffer 完整流程分析
android
用户69371750013843 小时前
不卷AI速度,我卷自己的从容——北京程序员手记
android·前端·人工智能
程序员Android3 小时前
Android 刷新一帧流程trace拆解
android
墨狂之逸才4 小时前
解决 Android/Gradle 编译报错:Comparison method violates its general contract!
android
阿明的小蝴蝶5 小时前
记一次Gradle环境的编译问题与解决
android·前端·gradle
汪海游龙5 小时前
开源项目 Trending AI 招募 Google Play 内测人员(12 名)
android·github