使用Bitmap.createBitmap () 比使用Bitmap.createScaledBitmap () 更快。
使用Bitmap.createBitmap ()我们已经通过了位图创建设置,而使用Bitmap.createScaledBitmap ()动态计算高度和宽度。
看例子:
/**
* 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