From 91f8a51a253b003990755678a11c7567bb818011 Mon Sep 17 00:00:00 2001 From: Burhanuddin Rashid Date: Mon, 11 Jun 2018 18:06:07 +0530 Subject: [PATCH] Extension property to get/set bitmap from ImageView --- .../androidx/core/widget/ImageViewTest.kt | 35 +++++++++++++++++++ .../java/androidx/core/widget/ImageView.kt | 28 +++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 src/androidTest/java/androidx/core/widget/ImageViewTest.kt create mode 100644 src/main/java/androidx/core/widget/ImageView.kt diff --git a/src/androidTest/java/androidx/core/widget/ImageViewTest.kt b/src/androidTest/java/androidx/core/widget/ImageViewTest.kt new file mode 100644 index 00000000..0cb9778d --- /dev/null +++ b/src/androidTest/java/androidx/core/widget/ImageViewTest.kt @@ -0,0 +1,35 @@ +package androidx.core.widget + +import android.graphics.Bitmap +import org.junit.Before +import android.support.test.InstrumentationRegistry +import android.widget.ImageView +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class ImageViewTest { + + private lateinit var fakeBitmap: Bitmap + private val context = InstrumentationRegistry.getContext() + + @Before + fun setup() { + val dim = 100 + fakeBitmap = Bitmap.createBitmap(dim, dim, Bitmap.Config.ARGB_8888) + } + + @Test + fun setBitmapTest() { + val imageView = ImageView(context) + imageView.bitmap = fakeBitmap + assertTrue(fakeBitmap.sameAs(imageView.bitmap)) + } + + @Test + fun emptyBitmapTest() { + val imageView = ImageView(context) + assertNull(imageView.bitmap) + } + +} \ No newline at end of file diff --git a/src/main/java/androidx/core/widget/ImageView.kt b/src/main/java/androidx/core/widget/ImageView.kt new file mode 100644 index 00000000..8fdb302f --- /dev/null +++ b/src/main/java/androidx/core/widget/ImageView.kt @@ -0,0 +1,28 @@ +package androidx.core.widget + +import android.graphics.Bitmap +import android.graphics.drawable.BitmapDrawable +import android.widget.ImageView + + +/** + * Returns Bitmap if set to imageview if not than it will return null + * + * ``` + * val myBitmap:Bitmap? = imageView.bitmap + * ``` + * + * Setting a bitmap to this property using [ImageView.setImageBitmap] + * + * ``` + * imageView.bitmap = myBitmap + * ``` + */ +inline var ImageView.bitmap: Bitmap? + get() { + val drawable = drawable as? BitmapDrawable + return drawable?.bitmap + } + set(value) { + setImageBitmap(value) + }