1 package org.robolectric.shadows; 2 3 import static org.robolectric.util.reflector.Reflector.reflector; 4 5 import android.graphics.Bitmap; 6 import android.graphics.Canvas; 7 import android.graphics.drawable.BitmapDrawable; 8 import org.robolectric.annotation.Implementation; 9 import org.robolectric.annotation.Implements; 10 import org.robolectric.annotation.RealObject; 11 import org.robolectric.shadow.api.Shadow; 12 import org.robolectric.util.reflector.Direct; 13 import org.robolectric.util.reflector.ForType; 14 15 @SuppressWarnings({"UnusedDeclaration"}) 16 @Implements(BitmapDrawable.class) 17 public class ShadowBitmapDrawable extends ShadowDrawable { 18 String drawableCreateFromStreamSource; 19 String drawableCreateFromPath; 20 21 @RealObject private BitmapDrawable realBitmapDrawable; 22 23 /** 24 * Draws the contained bitmap onto the canvas at 0,0 with a default {@code Paint} 25 * 26 * @param canvas the canvas to draw on 27 */ 28 @Implementation draw(Canvas canvas)29 protected void draw(Canvas canvas) { 30 if (ShadowView.useRealGraphics()) { 31 reflector(BitmapDrawableReflector.class, realBitmapDrawable).draw(canvas); 32 } else { 33 Bitmap bitmap = realBitmapDrawable.getBitmap(); 34 if (bitmap == null) { 35 return; 36 } 37 canvas.drawBitmap(bitmap, 0, 0, realBitmapDrawable.getPaint()); 38 } 39 } 40 41 @Override setCreatedFromResId(int createdFromResId, String resourceName)42 protected void setCreatedFromResId(int createdFromResId, String resourceName) { 43 super.setCreatedFromResId(createdFromResId, resourceName); 44 Bitmap bitmap = realBitmapDrawable.getBitmap(); 45 if (bitmap != null && Shadow.extract(bitmap) instanceof ShadowLegacyBitmap) { 46 ShadowLegacyBitmap shadowBitmap = Shadow.extract(bitmap); 47 if (shadowBitmap.createdFromResId == -1) { 48 shadowBitmap.setCreatedFromResId(createdFromResId, resourceName); 49 } 50 } 51 } 52 53 /** 54 * Returns the resource id that this {@code BitmapDrawable} was loaded from. This lets your tests 55 * assert that the bitmap is correct without having to actually load the bitmap. 56 * 57 * @return resource id from which this {@code BitmapDrawable} was loaded 58 * @deprecated use ShadowBitmap#getCreatedFromResId() instead. 59 */ 60 @Deprecated 61 @Override getCreatedFromResId()62 public int getCreatedFromResId() { 63 ShadowBitmap shadowBitmap = Shadow.extract(realBitmapDrawable.getBitmap()); 64 return shadowBitmap.getCreatedFromResId(); 65 } 66 getSource()67 public String getSource() { 68 return drawableCreateFromStreamSource; 69 } 70 getPath()71 public String getPath() { 72 return drawableCreateFromPath; 73 } 74 75 @ForType(BitmapDrawable.class) 76 interface BitmapDrawableReflector { 77 @Direct draw(Canvas canvas)78 void draw(Canvas canvas); 79 } 80 } 81