Converts SVG and Android Vector Drawable in Jetpack Compose code

Overview

SVG to Compose [Experimental]

Converts SVG or Android Vector Drawable to Compose code.

Why this project

On the start of the Compose for Desktop it does not support SVG files and Android Vector Drawables. This also difficulties a migration of the App to Multiplatform (Desktop and Android). Currently, it does support Android Vector Drawables in the Desktop allowing share your vectors.

Use cases

Now Compose for Desktop supports android vector drawables, this means that the first reason that the project was created does not apply anymore, this does not mean that it is not useful anymore.

Use cases:

  • Manipulate dynamic an SVG file in code, you can generate and do source code modifications.
  • Create an Icon pack similar to how Material Icons works on Compose (compose-icons is build with SVG to Compose)

How its work

The project uses Android's Svg2Vector to convert SVG to Android Drawables and uses a customized material icon code generator from the Jetpack Compose source code to generate the source code of the SVG file.

Example 1: Running with Kotlin Scripting

file: jetnews-drawables-to-compose.main.kts

@file:Repository("https://jitpack.io")
@file:Repository("https://maven.google.com")
@file:Repository("https://jetbrains.bintray.com/trove4j")

@file:DependsOn("com.github.DevSrSouza:svg-to-compose:-SNAPSHOT")
@file:DependsOn("com.google.guava:guava:23.0")
@file:DependsOn("com.android.tools:sdk-common:27.2.0-alpha16")
@file:DependsOn("com.android.tools:common:27.2.0-alpha16")
@file:DependsOn("com.squareup:kotlinpoet:1.7.2")
@file:DependsOn("org.ogce:xpp3:1.1.6")

import br.com.devsrsouza.svg2compose.Svg2Compose
import br.com.devsrsouza.svg2compose.VectorType
import java.io.File

val assetsDir = File("assets")
val srcDir = File("src/main/kotlin")

Svg2Compose.parse(
    applicationIconPackage = "assets",
    accessorName = "JetnewsAssets",
    outputSourceDirectory = srcDir,
    vectorsDirectory = assetsDir,
    type = VectorType.DRAWABLE,
    allAssetsPropertyName = "AllAssets"
)

Generating code by using executing kotlin jetnews-drawables-to-compose

Using in code: JetnewsAssets.JetnewsLogo

Svg

The only difference for SVG files is the VectorType.SVG.

Example 2: Generating a whole Icon pack

For Icon Packs, subgroups is supported: IconPack/group/icon.svg

val assetsDir = File("linea-icons")
val srcDir = File("src/main/kotlin")

Svg2Compose.parse(
    applicationIconPackage = "assets",
    accessorName = "LineaIcons",
    outputSourceDirectory = srcDir,
    vectorsDirectory = assetsDir,
    type = VectorType.SVG,
    iconNameTransformer = { name, group -> name.removePrefix(group) },
    allAssetsPropertyName = "AllIcons"
)

Using in code: LineaIcons.Arrows.Buhttps://github.com/overpas/svg-to-compose-intellijttonUp

The project also generate an accessor for all yours assets, for the given example, it should be LineaIcons.AllIcons and it also generated for child groups LineaIcons.Arrows.AllIcons

Comments
  • Fill by gradients not supported

    Fill by gradients not supported

    Hi, In the beginning, thx for the cool converter. I discovered filling color is null if used any gradient. For example, you can take this SVG and convert it to kt

    <svg height="150" width="400">
        <defs>
            <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
                <stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
            </linearGradient>
        </defs>
        <ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad1)" />
    </svg>
    
    public val ImagesGroup.Gradient: ImageVector
        get() {
            if (_gradient != null) {
                return _gradient!!
            }
            _gradient = Builder(
                name = "Gradient", defaultWidth = 400.0.dp, defaultHeight = 150.0.dp,
                viewportWidth = 400.0f, viewportHeight = 150.0f
            ).apply {
                path(
                    fill = null,
                    /* expected
                              Brush.linearGradient(
                                                  colors = listOf(Color.Yellow, Color.Red),
                                                  start = Offset(0f, 0f),
                                                  end = Offset(Float.POSITIVE_INFINITY, 0f)
                                              ),
                    */
                    stroke = null,
                    strokeLineWidth = 0.0f,
                    strokeLineCap = Butt,
                    strokeLineJoin = Miter,
                    strokeLineMiter = 4.0f,
                    pathFillType = NonZero
                ) {
                    moveTo(115.0f, 70.0f)
                    arcToRelative(85.0f, 55.0f, 0.0f, true, false, 170.0f, 0.0f)
                    arcToRelative(85.0f, 55.0f, 0.0f, true, false, -170.0f, 0.0f)
                    close()
                }
    
            }
                .build()
            return _gradient!!
        }
    
    private var _gradient: ImageVector? = null
    
    opened by jershell 7
  • Add licence file and headers to the project

    Add licence file and headers to the project

    This includes having licence file in the root of the repo as well as having licence headers in each file.

    The licence allows the tool to be used in commercial codebases and may be crucial for a lot of companies around. It's especially important now as Compose is being adopted by many for production.

    opened by bvitaliyg 2
  • IDE Plugin

    IDE Plugin

    Hi, I've created an Android Studio plugin wrapper around your project, in order to make it possible to generate icons in IDE. Here's it is https://github.com/overpas/svg-to-compose-intellij. It would be nice to hear your opinion on its reasonableness, usability, convenience, suggestions for improvement, etc. If you think it's worth the effort, could you mention it in the README of your project?

    opened by overpas 1
  • Fix imports for Compose beta08

    Fix imports for Compose beta08

    In Compose beta08 several classes that are used in vector graphics got transformed from enum class to inline class with values in companion object. See StrokeCap change for example. This changes broke static imports in generated code since now they should be referenced by companion object instead of top-level class. This PR should fix those import references.

    opened by vganin 0
  • [Question] Elaborate on the usage of Kotlin scripting

    [Question] Elaborate on the usage of Kotlin scripting

    Can you elaborate on how we can execute the scripting mentioned in the readme?

    Because running kotlin <something>.main.kts not working for me

    $ kotlin sample.main.kts
    :: problems summary ::
    :::: WARNINGS
    		module not found: com.github.DevSrSouza#svg-to-compose;0.8.1
    
    	==== central: tried
    
    	  https://repo1.maven.org/maven2/com/github/DevSrSouza/svg-to-compose/0.8.1/svg-to-compose-0.8.1.pom
    
    	  -- artifact com.github.DevSrSouza#svg-to-compose;0.8.1!svg-to-compose.jar:
    
    	  https://repo1.maven.org/maven2/com/github/DevSrSouza/svg-to-compose/0.8.1/svg-to-compose-0.8.1.jar
    
    error: cannot access script base class 'org.jetbrains.kotlin.mainKts.MainKtsScript'. Check your module classpath for missing or conflicting dependencies (sample.main.kts:1:1)
    error: unresolved reference: Repository (sample.main.kts:1:7)
    error: unresolved reference: Repository (sample.main.kts:2:7)
    error: unresolved reference: Repository (sample.main.kts:3:7)
    error: unresolved reference: DependsOn (sample.main.kts:5:7)
    error: unresolved reference: DependsOn (sample.main.kts:6:7)
    ...
    
    opened by esafirm 0
  • Static import of ImageVector.Builder cases compile error

    Static import of ImageVector.Builder cases compile error

    For a generated file:

    ..
    import androidx.compose.ui.graphics.vector.ImageVector
    import androidx.compose.ui.graphics.vector.ImageVector.Builder
    ..
    
    public val Icons.Coin: ImageVector
        get() {
            if (_coin != null) {
                return _coin!!
            }
            _coin = Builder(
                name = "Coin",
                defaultWidth = 24.0.dp,
                defaultHeight = 24.0.dp,
          ..
    

    The static import of the Builder here causes the following Compile Time Exception:

    <classpath>/icons/CoinKt.java:5: error: cannot access Builder
    import androidx.compose.ui.graphics.vector.ImageVector.Builder;
                                                          ^
      bad class file: /Users/nik/.gradle/caches/transforms-3/bd3521848bdffd1987d2b8593e215954/transformed/jetified-ui-1.3.0-api.jar(/androidx/compose/ui/graphics/vector/ImageVector$Builder.class)
        undeclared type variable: T
        Please remove or make sure it appears in the correct subdirectory of the classpath.
    

    By removing the static import and using _coin = ImageVector.Builder( ... it works fine.

    opened by nik-caspeco 0
  • Custom size generation

    Custom size generation

    1. Added support for Kotlin: 1.6.10 (other gradle updated): Tested.
    2. Added generation test assertions
    3. Added support for custom icon sizes
         Svg2Compose.parse(
                 ...,
                defaultSize:Int? = 0 // Should be float though  
        ) 
      
    opened by BreimerR 0
  • EOF Exception for some icons

    EOF Exception for some icons

    Issue

    • I try to convert bootstrap icons svg to compose. For the Fill icons it works, but for the normal icon it gives me exception. I have not checked which icon exactly that will cause the issue. But i have tried to use Svg2Vector to check if any of this svg will cause any error in the process.
    • Then i try to use the drawable and change the type to VectorType.DRAWABLE, but it still shows the same error.
    • Any suggestion to trace which icon that may cause the issue?

    Logcat

    Exception in thread "main" java.io.EOFException: input contained no data
    	at org.xmlpull.mxp1.MXParser.fillBuf(MXParser.java:3003)
    	at org.xmlpull.mxp1.MXParser.more(MXParser.java:3046)
    	at org.xmlpull.mxp1.MXParser.parseProlog(MXParser.java:1410)
    	at org.xmlpull.mxp1.MXParser.nextImpl(MXParser.java:1395)
    	at org.xmlpull.mxp1.MXParser.next(MXParser.java:1093)
    	at androidx.compose.material.icons.generator.IconParserKt.seekToStartTag(IconParser.kt:136)
    	at androidx.compose.material.icons.generator.IconParserKt.access$seekToStartTag(IconParser.kt:1)
    	at androidx.compose.material.icons.generator.IconParser.parse(IconParser.kt:40)
    	at androidx.compose.material.icons.generator.IconWriter.generateTo(IconWriter.kt:58)
    	at br.com.devsrsouza.svg2compose.Svg2Compose$parse$3.invoke(Svg2Compose.kt:92)
    	at br.com.devsrsouza.svg2compose.Svg2Compose$parse$3.invoke(Svg2Compose.kt:13)
    	at kotlin.io.FileTreeWalk$FileTreeWalkIterator$TopDownDirectoryState.step(FileTreeWalk.kt:168)
    	at kotlin.io.FileTreeWalk$FileTreeWalkIterator.gotoNext(FileTreeWalk.kt:98)
    	at kotlin.io.FileTreeWalk$FileTreeWalkIterator.computeNext(FileTreeWalk.kt:80)
    	at kotlin.collections.AbstractIterator.tryToComputeNext(AbstractIterator.kt:42)
    	at kotlin.collections.AbstractIterator.hasNext(AbstractIterator.kt:29)
    	at kotlin.sequences.SequencesKt___SequencesKt.toCollection(_Sequences.kt:742)
    	at kotlin.sequences.SequencesKt___SequencesKt.toMutableList(_Sequences.kt:772)
    	at kotlin.sequences.SequencesKt___SequencesKt.toList(_Sequences.kt:763)
    	at br.com.devsrsouza.svg2compose.Svg2Compose.parse(Svg2Compose.kt:138)
    	at br.com.devsrsouza.svg2compose.Svg2Compose.parse$default(Svg2Compose.kt:30)
    	at br.com.devsrsouza.svg2compose.MainKt.main(Main.kt:9)
    	at br.com.devsrsouza.svg2compose.MainKt.main(Main.kt)
    
    Process finished with exit code 1
    
    opened by wiryadev 0
Releases(0.8.1)
Owner
Gabriel Souza
Gabriel Souza
SvgToCompose - SVG path to Jetpack Compose tool

SvgToCompose SVG path to Jetpack Compose tool This tool can take the SVG path, and export it as a Jetpack Compose material icon path method calls. Exa

Mohsen Mirhoseini 43 Nov 9, 2022
Simple example how you can use dynamic color image vector in your app.

Dynamic Color ImageVector Simple example how you can use dynamic color image vector in your app. How to use 1. Create a xml image vector The content o

Lucas Martins 1 Oct 28, 2022
A simple authentication application using Jetpack compose to illustrate signin and sign up using Mvvm, Kotlin and jetpack compose

Authentication A simple authentication application using Jetpack compose to illustrate signin and sign up using Mvvm, Kotlin and jetpack compose Scree

Felix Kariuki 5 Dec 29, 2022
Compose-navigation - Set of utils to help with integrating Jetpack Compose and Jetpack's Navigation

Jetpack Compose Navigation Set of utils to help with integrating Jetpack Compose

Adam Kobus 5 Apr 5, 2022
Learn Jetpack Compose for Android by Examples. Learn how to use Jetpack Compose for Android App Development. Android’s modern toolkit for building native UI.

Learn Jetpack Compose for Android by Examples. Learn how to use Jetpack Compose for Android App Development. Android’s modern toolkit for building native UI.

MindOrks 382 Jan 5, 2023
A desktop code editor app using Jetpack Compose for Desktop and IntelliJ Platform

Compose Code Editor A desktop code editor app using Jetpack Compose for Desktop and IntelliJ Platform. Project Structure The code is contained in the

Alex 73 Dec 19, 2022
Jetpack Compose Boids | Flocking Insect 🐜. bird or Fish simulation using Jetpack Compose Desktop 🚀, using Canvas API 🎨

?? ?? ?? Compose flocking Ants(boids) ?? ?? ?? Jetpack compose Boids | Flocking Insect. bird or Fish simulation using Jetpack Compose Desktop ?? , usi

Chetan Gupta 38 Sep 25, 2022
A collection of animations, compositions, UIs using Jetpack Compose. You can say Jetpack Compose cookbook or play-ground if you want!

Why Not Compose! A collection of animations, compositions, UIs using Jetpack Compose. You can say Jetpack Compose cookbook or play-ground if you want!

Md. Mahmudul Hasan Shohag 186 Jan 1, 2023
This is a sample app(For beginners - App #2) built using Jetpack Compose. It demonstrates the concept of State Hoisting in Jetpack Compose.

JetBMICalculator This is a sample app(For beginners - App #2) built using Jetpack Compose. It demonstrates the concept of State Hoisting in Jetpack Co

BHAVNA THACKER 3 Dec 31, 2022
Jetpack-Compose-Demo - Instagram Profile UI using Jetpack Compose

Jetpack-Compose-Demo Instagram Profile UI using Jetpack Compose

omar 1 Aug 11, 2022
Jetpack-compose-animations-examples - Cool animations implemented with Jetpack compose

Jetpack-compose-animations-examples This repository consists of 4 animations: St

Canopas Software 180 Jan 2, 2023
Jetpack-compose-uis - A collection of some UIs using Jetpack Compose. built using Katalog

Jetpack Compose UIs This is a collection of some UIs using Jetpack Compose. It i

Mori Atsushi 3 Dec 15, 2022
Experimental Graphviz code generation POC built with Jetpack Compose compiler/runtime.

Compose Dot Experimental proof of concept to generate GraphViz dot code via Jetpack Compose's tree management. Valid dot file content can be generated

Arunkumar 29 Sep 14, 2022
Small code generating library for safe Jetpack Compose navigation with no boilerplate.

Compose Destinations A KSP library to use alongside compose navigation. It reduces boilerplate code and is less error-prone since passing arguments be

Rafael Costa 1.9k Jan 5, 2023
An application that i developed with a aim of learning Jetpack compose and many other jetpack libraries

An application that i developed with a aim of learning Jetpack compose and many other jetpack libraries, The application make use of jikan Api which displays a list of animations,there more details and even trailers of the animations.

Odhiambo Brandy 10 Nov 23, 2022
A Kotlin library to use Jetpack Compose in Android and iOS. Allow to write UI for both in Kotin. Still experimental as many compose features are not yet available.

Multiplatform Compose A Kotlin library to use Jetpack Compose in Android and iOS. Allow to write UI for both in Kotin. Still experimental as many comp

Clément Beffa 548 Jan 7, 2023
📱 WhatsApp clone project demonstrates modern Android development built with Jetpack Compose and Stream Chat SDK for Compose.

This is a WhatsApp clone app built with Jetpack Compose and Stream Chat SDK for Compose. The purpose of this repository is to demonstrate below: Imple

Stream 689 Dec 25, 2022
Jetpack Compose based project, used to stress-testing compose features / integrations and explore non-trivial functionality

Project containing Jetpack Compose samples For pagination & network images it uses CATAAS. Known issues Navigation-Compose Issue with fast tapping on

Denis Rudenko 59 Dec 14, 2022
Luis David Orellana 3 Jun 20, 2022