1 package org.robolectric.shadows; 2 3 import static android.os.Build.VERSION_CODES.LOLLIPOP; 4 import static org.robolectric.RuntimeEnvironment.getApiLevel; 5 import static org.robolectric.Shadows.shadowOf; 6 7 import android.graphics.Bitmap; 8 import android.graphics.BitmapFactory; 9 import android.graphics.BitmapRegionDecoder; 10 import android.graphics.Point; 11 import android.graphics.Rect; 12 import java.io.ByteArrayInputStream; 13 import java.io.FileDescriptor; 14 import java.io.FileInputStream; 15 import java.io.IOException; 16 import java.io.InputStream; 17 import org.robolectric.annotation.Implementation; 18 import org.robolectric.annotation.Implements; 19 import org.robolectric.util.ReflectionHelpers; 20 21 @Implements(BitmapRegionDecoder.class) 22 public class ShadowBitmapRegionDecoder { 23 private int width; 24 private int height; 25 26 @Implementation 27 public static BitmapRegionDecoder newInstance(byte[] data, int offset, int length, boolean isShareable) throws IOException { 28 return fillWidthAndHeight(newInstance(), new ByteArrayInputStream(data)); 29 } 30 31 @Implementation 32 public static BitmapRegionDecoder newInstance(FileDescriptor fd, boolean isShareable) throws IOException { 33 return fillWidthAndHeight(newInstance(), new FileInputStream(fd)); 34 } 35 36 @Implementation 37 public static BitmapRegionDecoder newInstance(InputStream is, boolean isShareable) throws IOException { 38 return fillWidthAndHeight(newInstance(), is); 39 } 40 41 @Implementation 42 public static BitmapRegionDecoder newInstance(String pathName, boolean isShareable) throws IOException { 43 return fillWidthAndHeight(newInstance(), new FileInputStream(pathName)); 44 } 45 46 private static BitmapRegionDecoder fillWidthAndHeight(BitmapRegionDecoder bitmapRegionDecoder, InputStream is) { 47 ShadowBitmapRegionDecoder shadowDecoder = shadowOf(bitmapRegionDecoder); 48 Point imageSize = ImageUtil.getImageSizeFromStream(is); 49 if (imageSize != null) { 50 shadowDecoder.width = imageSize.x; 51 shadowDecoder.height = imageSize.y; 52 } 53 return bitmapRegionDecoder; 54 } 55 56 @Implementation 57 public int getWidth() { 58 return width; 59 } 60 61 @Implementation 62 public int getHeight() { 63 return height; 64 } 65 66 @Implementation 67 public Bitmap decodeRegion(Rect rect, BitmapFactory.Options options) { 68 return Bitmap.createBitmap(rect.width(), rect.height(), 69 options.inPreferredConfig != null ? options.inPreferredConfig : Bitmap.Config.ARGB_8888); 70 } 71 72 private static BitmapRegionDecoder newInstance() { 73 if (getApiLevel() >= LOLLIPOP) { 74 return ReflectionHelpers.callConstructor(BitmapRegionDecoder.class, 75 new ReflectionHelpers.ClassParameter<>(long.class, 0L)); 76 } else { 77 return ReflectionHelpers.callConstructor(BitmapRegionDecoder.class, 78 new ReflectionHelpers.ClassParameter<>(int.class, 0)); 79 } 80 } 81 } 82