Nthily
03/15/2024, 8:10 PMmohamed rejeb
03/16/2024, 5:12 AM@Composable
fun loadSvgPainterFromBytes(bytes: ByteArray): Painter =
remember {
val svg = try {
SVGDOM(Data.makeFromBytes(bytes))
} catch (e: Exception) {
e.printStackTrace()
null
}
SvgPainter(svg)
}
class SvgPainter(
private val svg: SVGDOM?,
) : Painter() {
override var intrinsicSize: Size =
Size.Unspecified
override fun DrawScope.onDraw() {
if (svg == null) return
val svgWidth: Float
val svgHeight: Float
val viewBox: Rect? = svg.root?.viewBox
if (viewBox != null) {
svgWidth = viewBox.width
svgHeight = viewBox.height
} else {
svgWidth = svg.root?.width?.value ?: 0f
svgHeight = svg.root?.height?.value ?: 0f
}
// Set the SVG's view box to enable scaling if it is not set.
if (viewBox == null && svgWidth > 0f && svgHeight > 0f) {
svg.root?.viewBox = Rect.makeWH(svgWidth, svgHeight)
}
svg.root?.width = SVGLength(
value = 100f,
unit = SVGLengthUnit.PERCENTAGE,
)
svg.root?.height = SVGLength(
value = 100f,
unit = SVGLengthUnit.PERCENTAGE,
)
svg.setContainerSize(size.width, size.height)
svg.render(drawContext.canvas.nativeCanvas)
}
}
mohamed rejeb
03/16/2024, 5:12 AMSVGDOM
to draw an svg file on the canvas in any target other than Android.