背景:
flutter
嵌入原生view
时,原生view
使用的surfaveview
,导致下面两种方法无法正常使用。
- 导致
flutter
无法通过id
找到RenderRepaintBoundary
的toImage
来抓取widget
,- 原生层无法通过
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()));
}
}