【问题标题】:How can you compare two RippleDrawables?你如何比较两个 RippleDrawables?
【发布时间】:2016-10-03 06:06:44
【问题描述】:

我正在使用安卓Espresso。我想知道如何检查视图上使用的drawable 是否与规范中所述应使用的相同。我正在尝试比较drawableview 上使用的ConstantStates 和资源中的ConstantStates,但我没有得到任何结果。

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

【问题讨论】:

    标签: android android-espresso rippledrawable


    【解决方案1】:

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

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

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      • 2017-02-16
      • 2011-09-16
      • 2016-02-02
      • 2021-09-21
      相关资源
      最近更新 更多