Skip to content

Instantly share code, notes, and snippets.

@reza-id
Created November 20, 2018 11:07
Show Gist options
  • Save reza-id/d7a5f0f93bdd8c445cfbacf915daa978 to your computer and use it in GitHub Desktop.
Save reza-id/d7a5f0f93bdd8c445cfbacf915daa978 to your computer and use it in GitHub Desktop.
Espresso Custom View Matcher to check Vector Drawable Icon
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.StateListDrawable
import android.graphics.drawable.VectorDrawable
import android.support.annotation.DrawableRes
import android.support.test.espresso.matcher.BoundedMatcher
import android.support.v4.content.ContextCompat
import android.support.v7.view.menu.ActionMenuItemView
import android.view.View
import org.hamcrest.Description
import org.hamcrest.Matcher
/**
* 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>
*/
object CustomMatchers {
fun withIcon(@DrawableRes resourceId: Int): Matcher<View> {
return object : BoundedMatcher<View, ActionMenuItemView>(ActionMenuItemView::class.java) {
override fun describeTo(description: Description) {
description.appendText("has image drawable resource $resourceId")
}
public override fun matchesSafely(actionMenuItemView: ActionMenuItemView): Boolean {
return sameBitmap(actionMenuItemView.context, actionMenuItemView.itemData.icon, resourceId)
}
}
}
private fun sameBitmap(context: Context, drawable: Drawable?, resourceId: Int): Boolean {
var drawable = drawable
var otherDrawable: Drawable? = ContextCompat.getDrawable(context, resourceId)
if (drawable == null || otherDrawable == null) {
return false
}
if (drawable is StateListDrawable && otherDrawable is StateListDrawable) {
drawable = drawable.current
otherDrawable = otherDrawable.current
}
val bitmap = if (drawable is VectorDrawable) vectorToBitmap(drawable)
else (drawable as BitmapDrawable).bitmap
val otherBitmap = if (otherDrawable is VectorDrawable) vectorToBitmap(otherDrawable)
else (otherDrawable as BitmapDrawable).bitmap
return bitmap.sameAs(otherBitmap)
}
private fun vectorToBitmap(vectorDrawable: VectorDrawable): Bitmap {
val bitmap = Bitmap.createBitmap(vectorDrawable.intrinsicWidth, vectorDrawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
vectorDrawable.setBounds(0, 0, canvas.width, canvas.height)
vectorDrawable.draw(canvas)
return bitmap
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment