Skip to content

Instantly share code, notes, and snippets.

@dnanib
Created August 19, 2020 06:45
Show Gist options
  • Save dnanib/da534ce47cef5927952873c96d3fcf4c to your computer and use it in GitHub Desktop.
Save dnanib/da534ce47cef5927952873c96d3fcf4c to your computer and use it in GitHub Desktop.
A small Java class to take a screenshot of a View in Android
package com.example.lib.screenshots;
import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Handler;
import android.view.PixelCopy;
import android.view.View;
import javax.inject.Inject;
import com.example.dagger.ControllerScope;
@TargetApi(24)
@ControllerScope
public class ViewScreenshot {
public interface PostTake {
void onSuccess(Bitmap bitmap);
void onFailure(int error);
}
@Inject
public ViewScreenshot() {
}
@TargetApi(26)
public void take(View view, Activity activity, PostTake callback) {
if (callback == null) {
throw new IllegalArgumentException("Screenshot request without a callback");
}
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
int[] location = new int[2];
view.getLocationInWindow(location);
Rect rect = new Rect(location[0], location[1], location[0] + view.getWidth(), location[1] + view.getHeight());
PixelCopy.OnPixelCopyFinishedListener listener = new PixelCopy.OnPixelCopyFinishedListener() {
@Override
public void onPixelCopyFinished(int copyResult) {
if (copyResult == PixelCopy.SUCCESS) {
callback.onSuccess(bitmap);
} else {
callback.onFailure(copyResult);
}
}
};
try {
PixelCopy.request(activity.getWindow(), rect, bitmap, listener, new Handler());
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
@dnanib
Copy link
Author

dnanib commented Aug 19, 2020

Note: This is adapted from https://stackoverflow.com/a/50924037/642319

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment