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