0

I have a file:

res/drawable/test.svg

According to this answer I should be able to use painterResource to use it in JetpackCompose: https://stackoverflow.com/a/68579605/20009330

This is what I did:

Image(
        painter = painterResource(id = R.drawable.test),
        contentDescription = ""
)

But when I start typing R.drawable... the IDE typeahead-suggestions don't find the .svg, they only finds the other two .xml files (ic_launcher_background, ic_launcher_foreground) <- those are there by default when I am typing my R.drawable.

The R.drawable.'test' has a red font color now

See images for how it looks in AndroidStudio: enter image description here enter image description here

Do I need to convert those .svg files to another file format, e.g. xml before I can use them?

(Note: I tried simply renaming the .svg files to .xml but then got a runtime error so I think this is not the solution.)

Chef Lax
  • 89
  • 2
  • 10
  • 2
    The answer you are referencing is about compose for *Desktop*, not Android. In android, this is not possible. You can either convert it to vector drawable (xml), or use library that can load svgs, for example Coil. – Jan Bína Jan 04 '23 at 12:17
  • @Jan Should have posted this as the answer since it is indeed the solution. – Richard Onslow Roper Jan 04 '23 at 13:03

1 Answers1

0

Android supports a subset of SVG features via vector drawables, which can be stored in XML or created dynamically in code. In XML, it could look something like this:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="24dp"
    android:width="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
   <group
         android:name="rotationGroup"
         android:pivotX="10.0"
         android:pivotY="10.0"
         android:rotation="15.0" >
      <path
        android:name="vect"
        android:fillColor="#FF000000"
        android:pathData="M15.67,4H14V2h-4v2H8.33C7.6,4 7,4.6 7,5.33V9h4.93L13,7v2h4V5.33C17,4.6 16.4,4 15.67,4z"
        android:fillAlpha=".3"/>
      <path
        android:name="draw"
        android:fillColor="#FF000000"
        android:pathData="M13,12.5h2L11,20v-5.5H9L11.93,9H7v11.67C7,21.4 7.6,22 8.33,22h7.33c0.74,0 1.34,-0.6 1.34,-1.33V9h-4v3.5z"/>
   </group>
</vector>

That vector drawable would be stored in your res/drawable/ folder, allowing you to access it with the R.drawable.name syntax you were using.

To quickly convert between an SVG and an XML vector drawable, use the Resource Manager (top left or under the Tools menu), select the Drawable tab, press the + at the top left, and select Vector Asset. From that dialog, switch to Local file and pick your SVG, name, and other parameters.

Ian G. Clifton
  • 9,349
  • 2
  • 33
  • 34