Skip to content

Instantly share code, notes, and snippets.

@dilrajsingh1997
Created May 31, 2022 12:53
Show Gist options
  • Save dilrajsingh1997/4a6ec8212a910e1d1558aeca0f6de560 to your computer and use it in GitHub Desktop.
Save dilrajsingh1997/4a6ec8212a910e1d1558aeca0f6de560 to your computer and use it in GitHub Desktop.
Canvas(modifier = modifier,
onDraw = {
for (item in items) {
translate(top = item.y, left = item.x) {
drawContext.canvas.nativeCanvas.apply {
when (val itemToDraw = item.itemToDraw) {
is CanvasPath -> {
scale(
scale = item.scale,
pivot = Offset(
x = itemToDraw.path.getBounds().width / 2f,
y = itemToDraw.path.getBounds().height / 2f
)
) {
rotate(
degrees = item.angle,
pivot = Offset(
x = itemToDraw.path.getBounds().width / 2f,
y = itemToDraw.path.getBounds().height / 2f
)
) {
drawPath(
path = itemToDraw.path,
color = item.color.copy(alpha = item.alpha)
)
}
}
}
is CanvasText -> {
val textPaint = TextPaint().apply {
itemToDraw.paint(this)
color = android.graphics.Color.argb(
1,
(item.color.red * 255).toInt(),
(item.color.green * 255).toInt(),
(item.color.blue * 255).toInt()
)
alpha = (item.alpha * 255).toInt()
}
val bounds = Rect()
textPaint.getTextBounds(itemToDraw.text, 0, itemToDraw.text.length, bounds)
scale(
scale = item.scale,
pivot = Offset(
x = bounds.width() / 2f,
y = bounds.height() / 2f
)
) {
rotate(
degrees = item.angle,
pivot = Offset(
x = bounds.width() / 2f,
y = bounds.height() / 2f
)
) {
drawText(
itemToDraw.text,
0f,
bounds.height().toFloat(),
textPaint
)
}
}
}
is CanvasObject -> {
itemToDraw.objectToDraw(this@translate, item.alpha, item.angle, item.color, item.scale)
}
}
}
}
}
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment