ChatGPT解决这个技术问题 Extra ChatGPT

What is the easiest way to use SVG images in Android?

I have found a myriad of libraries in order to use SVG images in Android and avoid the frustrating creation of different resolutions and dropping files for each resolution. This becomes very annoying when the app has many icons or images.

What would be a step-by-step process of the simplest-to-use library for using SVG images in Android?

Also I use Android Studio and Illustrator for generating my icons and images.

Short video on how to import svg in android studio: youtube.com/watch?v=8e3I-PYJNHg

P
Peter Mortensen

First you need to import SVG files by the following simple steps.

Right click on your project's drawable folder (app/res/drawable) Click New Select Vector Asset

If the image is available in your computer then select the local svg file.

After that, select the image path. An option to change the size of the image is also available at the right side of dialog if you want to. In this way, the SVG image is imported in your project.

After that, for using this image, use the same procedure:

@drawable/yourimagename

Short and useful answer, without headache when you do import external svg files to project.
the Next button is always disabled. any idea why ?
So, how do we change the color of the svg?
@mrid if it is something you have to do just once you may use Inkscape or vectr.com (for free) or Adobe Illustrator etc..
There is a bug in Android Studio that does so that sometimes you will need to open res/drawable/file.xml (a file that's created automatically when you import the SVG file) and replace every occurrence of with -. If you don't do that, your app will crash. See my bug report here: issuetracker.google.com/issues/195687730
P
Peter Mortensen

UPDATE: DO NOT use this old answer. Better use Pallavi Jain's answer

I found svg-android to be quite easy to use, so the step-by-step instructions are here:

Download the library from: https://code.google.com/p/svg-android/downloads/list. The latest version at the moment of writing this is: svg-android-1.1.jar Put the JAR file in the lib directory. Save your *.svg file in the res/drawable directory (in Illustrator, it is as easy as pressing Save as and select .svg) Code the following in your activity using the SVG library: ImageView imageView = (ImageView) findViewById(R.id.imgView); SVG svg = SVGParser.getSVGFromResource(getResources(), R.drawable.example); // The following is needed because of image accelaration in some devices, such as Samsung imageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); imageView.setImageDrawable(svg.createPictureDrawable());

You can reduce the boilerplate code like this:

Very easily I made a simple class to contain the past code and reduce the boilerplate code, like this:

import android.app.Activity;
import android.view.View;
import android.widget.ImageView;

import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParser;

public class SvgImage {

    private static ImageView imageView;
    private Activity activity;
    private SVG svg;
    private int xmlLayoutId;
    private int drawableId;


    public SvgImage(Activity activity, int layoutId, int drawableId) {
        imageView = (ImageView) activity.findViewById(layoutId);
        svg = SVGParser.getSVGFromResource(activity.getResources(), drawableId);
        // Needed because of image acceleration in some devices, such as Samsung
        imageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        imageView.setImageDrawable(svg.createPictureDrawable());
    }
}

Now I can call it like this in activity:

    SvgImage rainSVG = new SvgImage(MainActivity.this, R.id.rainImageView, R.drawable.rain);
    SvgImage thunderSVG = new SvgImage(MainActivity.this, R.id.thunderImageView, R.drawable.thunder);
    SvgImage oceanSVG = new SvgImage(MainActivity.this, R.id.oceanImageView, R.drawable.ocean);
    SvgImage fireSVG = new SvgImage(MainActivity.this, R.id.fireImageView, R.drawable.fire);
    SvgImage windSVG = new SvgImage(MainActivity.this, R.id.windImageView,R.drawable.wind);
    SvgImage universeSVG = new SvgImage(MainActivity.this, R.id.universeImageView,R.drawable.universe);

When I try to add SVG files I am getting error saying, Error: The file name must end with .xml or .png
Why is imageView static? I see a hugh red bug flag here. SvgImage rainSVG = new SvgImage(MainActivity.this, R.id.rainImageView, R.drawable.rain); SvgImage thunderSVG = new SvgImage(MainActivity.this, R.id.thunderImageView, R.drawable.thunder); rainSVG does reference contain thunderImageView
@DSchmidt that is just a pointer to the imageview. If it was my code I would make the whole class static with one method called LoadSVG. and as you can see there is no point of loading data to private variables that can not be accessed.
P
Pradeep Mahdevu

Android Studio supports SVG from 1.4 onwards

Here is a video on how to import.


P
Peter Mortensen

Try this:

https://i.stack.imgur.com/NulKz.png

The next step:

https://i.stack.imgur.com/OXqKn.png

And now edit the image or icon name and save it:

https://i.stack.imgur.com/jAjGU.png


Step by step i like it, save my life!
This is missing a whole lot. What application is this? Android Studio? In what context and how is "Vector Asset" being invoked (adding it? - adding it to what?)? A context menu? Where and what? Why is "Vector Asset" being invoked? What is the idea? What is the general idea? Importing SVG files into Android Studio? Something else? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
P
Peter Mortensen

Rather than adding libraries which increases your APK file size, I will suggest you to convert SVG to drawable using Android SVG to VectorDrawable.

And add vectorDrawables.useSupportLibrary = true in Gradle.


P
Peter Mortensen

1. You need to convert SVG to XML to use in an Android project.

1.1 You can do this with Android SVG to VectorDrawable, but it does not support all the features of SVG, like some gradients.

1.2 You can convert via Android Studio, but it might use some features that only supports API 24 and higher that cause crashes your app in older devices.

And add vectorDrawables.useSupportLibrary = true in the Gradle file and use it like this:

<android.support.v7.widget.AppCompatImageView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:srcCompat="@drawable/ic_item1" />

2. Use this library SVG-Android that supports these features

Add this code in the application class:

public void onCreate() {
    SVGLoader.load(this)
}

And use the SVG like this:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_android_red"/>

Why use an SVG loader when you have @Pallavi's straight forward approach? Is there any advantage to using a loader?
@Taslim the supported features is more than the usual way. you can see the supported features and see.
P
Peter Mortensen

You can use the Coil library to load an SVG file. Just add these lines in file build.gradle:

// ... Coil (https://github.com/coil-kt/coil)
implementation("io.coil-kt:coil:0.12.0")
implementation("io.coil-kt:coil-svg:0.12.0")

Then add an extension function:

fun AppCompatImageView.loadSvg(url: String) {
    val imageLoader = ImageLoader.Builder(this.context)
        .componentRegistry { add(SvgDecoder(this@loadSvg.context)) }
        .build()

    val request = ImageRequest.Builder(this.context)
        .crossfade(true)
        .crossfade(500)
        .data(url)
        .target(this)
        .build()

    imageLoader.enqueue(request)
}

Then call this method in your activity or fragment:

your_image_view.loadSvg("your_file_name.svg")

Coil uses this tool bigbadaboom.github.io/androidsvg
R
Rahul Thakur

Try the SVG2VectorDrawable Plugin. Go to Preferences → Plugins → Browse Plugins and install SVG2VectorDrawable. It is great for converting svg files to vector drawable.

Once you have installed you will find an icon for this in the toolbar section just to the right of the help (?) icon.


Doesn't work for me - the SVG file path doesn't even get uploaded into the plugin. The best answer above is much simpler, and gets the job done.
Great plugin - quickly converted many svg's to vector drawables!
What is a "sag file"? Do you mean "SVG file"? Or something else?
P
Peter Mortensen

Right-click on the drawable directory, press New, and then go to Vector assets Change the asset type from clip art to local Browse your file Input the size Then click Next and then Done

Your usable SVG image will be generated in the drawable directory.


M
Mattia Ferigutti

Load SVGs using the Coil library. Note that this library is built upon Kotlin Coroutines.

Import the extension library:

implementation("io.coil-kt:coil-svg:2.1.0")

And add the decoder to your component registry when constructing your

ImageLoader:
val imageLoader = ImageLoader.Builder(context)
    .components {
        add(SvgDecoder.Factory())
    }
    .build()

That's it!

Click here for more information.