猿问

比较Android中的两个drawables

如何比较两个可绘制对象,我这样做却没有成功


public void MyClick(View view)

{

 Drawable fDraw = view.getBackground();

 Drawable sDraw = getResources().getDrawable(R.drawable.twt_hover);


  if(fDraw.equals(sDraw))

  {

   //Not coming

  }

}


阿晨1998
浏览 404回答 3
3回答

暮色呼如

依靠getConstantState()单独可导致假阴性。我采用的方法是尝试在第一个实例中比较ConstantState,但是如果该检查失败,则退回到Bitmap比较中。这在所有情况下都应适用(包括不是资源的图像),但请注意,这会占用大量内存。public static boolean areDrawablesIdentical(Drawable drawableA, Drawable drawableB) {&nbsp; &nbsp; Drawable.ConstantState stateA = drawableA.getConstantState();&nbsp; &nbsp; Drawable.ConstantState stateB = drawableB.getConstantState();&nbsp; &nbsp; // If the constant state is identical, they are using the same drawable resource.&nbsp; &nbsp; // However, the opposite is not necessarily true.&nbsp; &nbsp; return (stateA != null && stateB != null && stateA.equals(stateB))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || getBitmap(drawableA).sameAs(getBitmap(drawableB));}public static Bitmap getBitmap(Drawable drawable) {&nbsp; &nbsp; Bitmap result;&nbsp; &nbsp; if (drawable instanceof BitmapDrawable) {&nbsp; &nbsp; &nbsp; &nbsp; result = ((BitmapDrawable) drawable).getBitmap();&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; int width = drawable.getIntrinsicWidth();&nbsp; &nbsp; &nbsp; &nbsp; int height = drawable.getIntrinsicHeight();&nbsp; &nbsp; &nbsp; &nbsp; // Some drawables have no intrinsic width - e.g. solid colours.&nbsp; &nbsp; &nbsp; &nbsp; if (width <= 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; width = 1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (height <= 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; height = 1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);&nbsp; &nbsp; &nbsp; &nbsp; Canvas canvas = new Canvas(result);&nbsp; &nbsp; &nbsp; &nbsp; drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());&nbsp; &nbsp; &nbsp; &nbsp; drawable.draw(canvas);&nbsp; &nbsp; }&nbsp; &nbsp; return result;}

德玛西亚99

我的问题是仅比较两个可绘制对象,我尝试但无法获得直接比较两个可绘制对象的任何方法,但是对于我的解决方案,我将可绘制对象更改为位图,然后比较两个位图,此方法是可行的。Bitmap bitmap = ((BitmapDrawable)fDraw).getBitmap();Bitmap bitmap2 = ((BitmapDrawable)sDraw).getBitmap();if(bitmap == bitmap2)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //Code blcok&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Android
我要回答