So far, what other good way to load SVG images on ...
# compose-web
n
So far, what other good way to load SVG images on Compose For Web? 🤔 It seems that SVG files can only be converted to XML to be displayed on the web platform at the moment
m
d
Copy code
@Composable
fun loadSvgPainterFromBytes(bytes: ByteArray): Painter =
    remember {
        val svg = try {
            SVGDOM(Data.makeFromBytes(bytes))
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
        SvgPainter(svg)
    }
Copy code
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)
    }
}
You can use
SVGDOM
to draw an svg file on the canvas in any target other than Android.
❤️ 1