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()));
	}
}
相关推荐
国服第二切图仔24 分钟前
Electron for鸿蒙PC实战项目之简易绘图板应用
android·electron·开源鸿蒙·鸿蒙pc
BD_Marathon34 分钟前
【IDEA】常用插件——3
android·java·intellij-idea
北海道浪子38 分钟前
Android 开发中的图片格式全指南
android·架构
lichong95141 分钟前
RelativeLayout 根布局里有一个子布局预期一直展示,但子布局RelativeLayout被 覆盖了
android·java·前端
弥巷1 小时前
【Android】Binder机制浅析
android
不会写代码的猴子1 小时前
安卓兼容性框架变更记录
android
无风之翼1 小时前
android12下拉菜单栏界面上方显示无内容
android·java
6***94151 小时前
MySQL 字符串日期格式转换
android·数据库·mysql
p***q781 小时前
MySQL——用户管理
android·mysql·adb
g***86691 小时前
MySQL - Navicat自动备份MySQL数据
android·数据库·mysql