Skip to content

Instantly share code, notes, and snippets.

@d4rken
Last active August 28, 2019 10:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d4rken/3b5c9cdb60c16fa4c4371774a1c5c9c0 to your computer and use it in GitHub Desktop.
Save d4rken/3b5c9cdb60c16fa4c4371774a1c5c9c0 to your computer and use it in GitHub Desktop.
Android InstrumentationTest Espresso matcher for Drawable's
/**
* Apache 2.0
*
* @see <a href="https://github.com/stablekernel/EspressoLib/blob/master/src/main/java/com/stablekernel/espressolib/DrawableMatcher.java">Source1</a>
* @see <a href="http://stackoverflow.com/questions/33696488/getting-bitmap-from-vector-drawable">Source2</a>
*/
@SuppressWarnings("SimplifiableIfStatement")
public class DrawableMatcher extends TypeSafeMatcher<View> {
private final int expectedResourceId;
public DrawableMatcher(@DrawableRes int expectedResourceId) {
super(View.class);
this.expectedResourceId = expectedResourceId;
}
@Override
protected boolean matchesSafely(View item) {
if (!(item instanceof ImageView)) return false;
ImageView imageView = (ImageView) item;
if (expectedResourceId == 0) return imageView.getDrawable() == null;
Drawable expectedDrawable = ContextCompat.getDrawable(item.getContext(), expectedResourceId);
if (expectedDrawable == null) return false;
Drawable actualDrawable = imageView.getDrawable();
if (expectedDrawable instanceof VectorDrawable) {
if (!(actualDrawable instanceof VectorDrawable)) return false;
return vectorToBitmap((VectorDrawable) expectedDrawable).sameAs(vectorToBitmap((VectorDrawable) actualDrawable));
}
if (expectedDrawable instanceof BitmapDrawable) {
if (!(actualDrawable instanceof BitmapDrawable)) return false;
return ((BitmapDrawable) expectedDrawable).getBitmap().sameAs(((BitmapDrawable) actualDrawable).getBitmap());
}
throw new IllegalArgumentException("Unsupported drawable: " + imageView.getDrawable());
}
private static Bitmap vectorToBitmap(VectorDrawable vectorDrawable) {
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
vectorDrawable.draw(canvas);
return bitmap;
}
@Override
public void describeTo(Description description) {
description.appendText("with drawable id: ").appendValue(expectedResourceId);
}
}
@momvart
Copy link

momvart commented Aug 28, 2019

line 22: if (expectedResourceId < 0) should be if (expectedResourceId == 0).
Resources may have negative ids.

@d4rken
Copy link
Author

d4rken commented Aug 28, 2019

line 22: if (expectedResourceId < 0) should be if (expectedResourceId == 0).
Resources may have negative ids.

Thanks

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