Android 原生层SurfaceView截屏

发布于:2025-02-14 ⋅ 阅读:(95) ⋅ 点赞:(0)

背景:flutter嵌入原生view时,原生view使用的surfaveview,导致下面两种方法无法正常使用。

  1. 导致flutter无法通过id找到RenderRepaintBoundarytoImage来抓取widget
  2. 原生层无法通过view去获取Bitmap

方案:使用PixelCopy方法抓取屏幕像素数据,并且复制到Bitmap

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()));
	}
}

网站公告

今日签到

点亮在社区的每一天
去签到