Created
February 14, 2019 06:54
-
-
Save yumi0629/1d0a3ffea35db0fb84ba1e4ad412f178 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 拼接bitmap | |
* @param bgColor 画布颜色,默认为null,透明色 | |
*/ | |
fun combineBitmaps(vararg bitmaps: Bitmap, bgColor: Int? = null, direction: CombineDirection = CombineDirection.Vertical, maxLength: Int? = null): Bitmap { | |
var height = 0 | |
var width = 0 | |
// 计算组合后宽高 | |
loop@ for (bitmap in bitmaps) { | |
when (direction) { | |
CombineDirection.Horizontal -> { | |
width += bitmap.width | |
if (maxLength != null) continue@loop | |
if (bitmap.height > height) { | |
height = bitmap.height | |
} | |
} | |
CombineDirection.Vertical -> { | |
height += bitmap.height | |
if (maxLength != null) continue@loop | |
if (bitmap.width > width) { | |
width = bitmap.width | |
} | |
} | |
} | |
} | |
maxLength?.let { | |
when (direction) { | |
CombineDirection.Horizontal -> height = maxLength | |
CombineDirection.Vertical -> width = maxLength | |
} | |
} | |
val bigBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) | |
val bigCanvas = Canvas(bigBitmap) | |
// draw background if necessary | |
bgColor?.let { bigCanvas.drawColor(it) } | |
var iOffset = 0f | |
for (bitmap in bitmaps) { | |
iOffset += when (direction) { | |
CombineDirection.Horizontal -> { | |
bigCanvas.drawBitmap(bitmap, iOffset, (height - bitmap.height) * 0.5f, Paint()) | |
bitmap.width | |
} | |
CombineDirection.Vertical -> { | |
bigCanvas.drawBitmap(bitmap, (width - bitmap.width) * 0.5f, iOffset, Paint()) | |
bitmap.height | |
} | |
} | |
} | |
return bigBitmap | |
} | |
enum class CombineDirection { | |
Vertical, | |
Horizontal, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment