Using Bitmap.createBitmap () becomes faster than using Bitmap.createScaledBitmap ().
Using Bitmap.createBitmap () we have already passed the Bitmap creation settings, while with Bitmap.createScaledBitmap () height and width are calculated dynamically.
See the example:
/**
* Return a [Bitmap] representation of this [Drawable].
*
* If this instance is a [BitmapDrawable] and the [width], [height], and [config] match, the
* underlying [Bitmap] instance will be returned directly. If any of those three properties differ
* then a new [Bitmap] is created. For all other [Drawable] types, a new [Bitmap] is created.
*
* @param width Width of the desired bitmap. Defaults to [Drawable.getIntrinsicWidth].
* @param height Height of the desired bitmap. Defaults to [Drawable.getIntrinsicHeight].
* @param config Bitmap config of the desired bitmap. Null attempts to use the native config, if
* any. Defaults to [Config.ARGB_8888] otherwise.
*/
fun Drawable.toBitmap(
@Px width: Int = intrinsicWidth,
@Px height: Int = intrinsicHeight,
config: Config? = null
): Bitmap {
if (this is BitmapDrawable) {
if (config == null || bitmap.config == config) {
// Fast-path to return original. Bitmap.createScaledBitmap will do this check, but it
// involves allocation and two jumps into native code so we perform the check ourselves.
if (width == intrinsicWidth && height == intrinsicHeight) {
return bitmap
}
return Bitmap.createScaledBitmap(bitmap, width, height, true)
}
}
val (oldLeft, oldTop, oldRight, oldBottom) = bounds
val bitmap = Bitmap.createBitmap(width, height, config ?: Config.ARGB_8888)
setBounds(0, 0, width, height)
draw(Canvas(bitmap))
setBounds(oldLeft, oldTop, oldRight, oldBottom)
return bitmap
}
Source