diff options
Diffstat (limited to 'library/src/main/kotlin/ca/allanwang/kau/utils/Utils.kt')
-rw-r--r-- | library/src/main/kotlin/ca/allanwang/kau/utils/Utils.kt | 23 |
1 files changed, 21 insertions, 2 deletions
diff --git a/library/src/main/kotlin/ca/allanwang/kau/utils/Utils.kt b/library/src/main/kotlin/ca/allanwang/kau/utils/Utils.kt index c44fc9a..6c1b6a1 100644 --- a/library/src/main/kotlin/ca/allanwang/kau/utils/Utils.kt +++ b/library/src/main/kotlin/ca/allanwang/kau/utils/Utils.kt @@ -1,9 +1,11 @@ package ca.allanwang.kau.utils import android.content.Context -import android.content.pm.PackageManager import android.content.res.Resources -import android.os.Build +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.drawable.BitmapDrawable +import android.graphics.drawable.Drawable import android.os.Looper import android.support.annotation.IntRange import ca.allanwang.kau.R @@ -56,4 +58,21 @@ annotation class KauUtils val formatter = DecimalFormat(expression.toString()) formatter.roundingMode = RoundingMode.HALF_UP return formatter.format(this) +} + +@KauUtils fun Drawable.toBitmap(scaling: Float = 1f): Bitmap { + if (this is BitmapDrawable && bitmap != null) { + if (scaling == 1f) return bitmap + val width = (bitmap.width * scaling).toInt() + val height = (bitmap.height * scaling).toInt() + return Bitmap.createScaledBitmap(bitmap, width, height, false) + } + val bitmap = if (intrinsicWidth <= 0 || intrinsicHeight <= 0) + Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) // Single color bitmap will be created of 1x1 pixel + else + Bitmap.createBitmap((intrinsicWidth * scaling).toInt(), (intrinsicHeight * scaling).toInt(), Bitmap.Config.ARGB_8888) + val canvas = Canvas(bitmap) + setBounds(0, 0, canvas.width, canvas.height) + draw(canvas) + return bitmap }
\ No newline at end of file |