你怎么比较两个RippleDrawables?

时间:2016-10-03 06:06:44

标签: android android-espresso rippledrawable

我正在使用android Espresso。我想知道如何检查视图上使用的drawable是否与规范中所述应该使用的相同。我正在尝试比较ConstantStatesdrawable使用的view和参考资料中的ImageTarget,但我没有得到任何结果。

有办法做到这一点吗?或者在自动化测试方面完全不需要这项检查?

1 个答案:

答案 0 :(得分:0)

为了比较我已经使用过这段代码的两张图片:

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;
}
}

希望它会有所帮助