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()));
	}
}
相关推荐
你过来啊你1 小时前
Android用户鉴权实现方案深度分析
android·鉴权
kerli3 小时前
Android 嵌套滑动设计思想
android·客户端
恣艺4 小时前
LeetCode 854:相似度为 K 的字符串
android·算法·leetcode
阿华的代码王国5 小时前
【Android】相对布局应用-登录界面
android·xml·java
用户207038619496 小时前
StateFlow与SharedFlow如何取舍?
android
QmDeve6 小时前
原生Android Java调用系统指纹识别方法
android
淹没6 小时前
🚀 告别复杂的HTTP模拟!HttpHook让Dart应用测试变得超简单
android·flutter·dart
HX4367 小时前
MP - List (not just list)
android·ios·全栈