PixelCopy 将 Surface 转成 Bitmap

PixelCopy 是 Android 8.0 新增的类,支持传入 Surface/Window。生成的截图包含阴影裁剪

1
2
3
4
5
6
7
public static void request(@NonNull Surface source, @Nullable Rect srcRect,
@NonNull Bitmap dest, @NonNull OnPixelCopyFinishedListener listener,
@NonNull Handler listenerThread)

public static void request(@NonNull Window source, @Nullable Rect srcRect,
@NonNull Bitmap dest, @NonNull OnPixelCopyFinishedListener listener,
@NonNull Handler listenerThread)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public static void convertLayoutToBitmap(Activity activity, OnConvertBitmapListener listener) {
if (activity == null || activity.isFinishing()) {
return;
}
Window window = activity.getWindow();
View view = window.getDecorView();
Rect rect = new Rect(0, 0, view.getWidth(), view.getHeight());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Bitmap dest = Bitmap.createBitmap(rect.width(), rect.height(), Bitmap.Config.RGB_565);
android.view.PixelCopy.request(window, rect, dest, new PixelCopy.OnPixelCopyFinishedListener() {
@Override
public void onPixelCopyFinished(int copyResult) {
if (copyResult == android.view.PixelCopy.SUCCESS) {
listener.onSuccess(dest);
}else {
listener.onFailure();
}
}
}, new Handler(Looper.getMainLooper()));
}else{
listener.onSuccess(getBitmapFromView(view));
}
}

public static Bitmap getBitmapFromView(View v) {
if (null == v) {
return null;
}
v.setDrawingCacheEnabled(true); //注意child 如果设置了 enable可能会导致获取的截图不更新。可循环遍历看看是哪个 view
Bitmap drawingCache = v.getDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(drawingCache);
v.setDrawingCacheEnabled(false);
return bitmap;
}

public interface OnConvertBitmapListener {
void onSuccess(Bitmap bm);

void onFailure();
}

8.0 以下版本使用 View.getDrawingCache 来兼容

文章来自: https://hanks.pub