如何比较两个RippleDrawables?
问题描述:
我正在使用android Espresso
。我想知道如何检查在视图中使用的drawable
是否与规格中所述应该使用的相同。我试图比较view
上使用drawable
的ConstantStates
和资源中的ConstantStates
,但我没有得到任何地方。如何比较两个RippleDrawables?
有没有办法做到这一点?或者当它涉及到自动化测试时,这种检查完全不需要吗?
答
用于比较两个图像,我已经使用这个代码:
public class ImageComparator {
public static Matcher<View> withImageResource(final int imageResourceId) {
return new TypeSafeMatcher<View>() {
@Override
public void describeTo(Description description) {
description.appendText("with drawable from resource id: " + imageResourceId);
}
@Override
public boolean matchesSafely(View view) {
Drawable actualDrawable = ((ImageView) view).getDrawable();
final Drawable correctDrawable = view.getResources().getDrawable(imageResourceId);
if (actualDrawable == null) {
return correctDrawable == null;
}
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return areImagesTheSameAfterSdk21(actualDrawable, correctDrawable);
} else {
return areImagesTheSameBeforeSdk21(actualDrawable, correctDrawable);
}
}
};
}
protected static boolean areImagesTheSameBeforeSdk21(Drawable actualDrawable,
Drawable correctDrawable) {
Drawable.ConstantState actualDrawableConstantState = actualDrawable.getConstantState();
Drawable.ConstantState correctDrawableConstantState = correctDrawable.getConstantState();
return actualDrawableConstantState.equals(correctDrawableConstantState);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
protected static boolean areImagesTheSameAfterSdk21(Drawable actualDrawable,
Drawable correctDrawable) {
Bitmap correctBitmap = drawableToBitmap(correctDrawable);
Bitmap actualBitmap = drawableToBitmap(actualDrawable);
return correctBitmap.sameAs(actualBitmap);
}
private static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
Bitmap bitmap = Bitmap
.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
}
希望这将有助于