java - 在原生 java 中截取屏幕截图并在颤动中显示此屏幕截图
问题描述
想用原生Java截取手机屏幕截图。将这个截图位图存储在一个 byte[] 数组中,通过平台通道将这个 byte[] 数组传递给flutter,最后想在一个flutter应用程序中显示这个截图。
本机 Java 代码:
public Bitmap takeScreenshot(){
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public byte[] bitmapToByte(){
Bitmap bitmap = takeScreenshot();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] array = stream.toByteArray();
Log.i("MyAndroidClass", Arrays.toString(array));
return array;
}
public File saveBitmap(Bitmap bitmap){
Bitmap bitmap = takeScreenshot();
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshoot.png");
FileOutputStream fos;
try{
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
return imagePath;
}
飞镖平台频道:
Future<Null> _takeScreenShot() async {
Uint8List screenShot;
Uint8List ssView = await platform2.invokeMethod("takeScreenshot");
screenShot = ssView;
print(screenShot);
setState(() {
byteView = screenShot;
});
}
Flutter UI 显示截图:
Container(
child: byteView != null
? Image.memory(
byteView,
width: 100,
height: 150,
)
: Container(),
),
print(screenshot)
显示一个 byte[] 数组:
[137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 4, 56, 0, 0, 7, 128, 8, 2, 0, 0, 0, 164, 3, 112, 93, 0, 0, 0, 3, 115, 66, 73, 84, 8, 8, 8, 219, 225, 79, 224, 0, 0, 32, 0, 73, 68, 65, 84, 120, 156, 236, 221, 187, 138, 20, 81, 20, 64, 209, 115, 155, 198, 119, 160, 129, 162, 160, 32, 38, 130, 255, 228, 159, 248, 165, 134, 26, 136, 10, 130, 207, 81, 25, 186, 12, 156, 25, 17, 140, 237, 13, 179, 86, 80, 20, 197, 13, 78, 186, 57, 69, 213, 122, 254, 98, 46, 172, 53, 107, 247, 251, 110, 0, 0, 0, 254, 135, 109, 102, 102, 14, 115, 216, 254, 60, 219, 255, 227, 208, 58, 63, 10, 0, 0, 112, 12, 103, 161, 178, 109, 51, 219, 28, 182, 57, 28, 102, 89, 167, 0, 0, 0, 255, 215, 90, 179, 214, 204, 58, 235, 145, 243, 141, 202, 54, 223, 79, 230, 219, 167, 249, 246, 249, 252, 220, 113, 198, 3, 0, 0, 46, 163, 171, 55, 230, 230, 237, 185, 118, 99, 214, 110, 102, 155, 253, 110, 205, 54, 115, 216, 230, 235, 199, 121, 251, 106, 222, 191, 58, 246, 128, 0, 0, 192, 229, 115, 231, 254, 60, 120, 50, 87, 174, 206, 126, 63,
解决方案
实现此目的的一种简单方法是将屏幕截图另存为磁盘上的文件,然后将文件路径简单地传递给颤振。然后你使用Image.file加载它
推荐阅读
- javafx - 场景构建器中的 Javafx 表视图未插入用户输入
- laravel - 带控制器的智能路由
- python-3.x - Python字典项目问题
- ios - 从一个视图控制器切换到另一个视图控制器,无需用户交互
- java - Kotlin Jar 错误:线程“Timer-0”java.lang.NoSuchMethodError 中的异常
- java - ArrayList 和继承与多态和复制构造函数
- c# - 我的控制台应用程序出错“程序不包含适合入口点的静态‘主要’方法”
- xpath - 如何使用 XPATH 分别获取每个值
- android - Android:MainActivity 中的方法工作正常,通过 BroadcastReceiver 类在 MainActivity 中运行相同的方法会给出空指针
- javascript - 调整 javascript 行