Created
August 19, 2020 06:45
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: This is adapted from https://stackoverflow.com/a/50924037/642319