Easiest way to use SVG in Android?

前端 未结 8 999
一个人的身影
一个人的身影 2020-12-02 05:35

I have found a myriad of libraries in order to use svg in Android and avoid the frustrating creation of different resolutions and dropping files for each resolution, this be

8条回答
  •  Happy的楠姐
    2020-12-02 05:52

    UPDATE: DO NOT use this old answer, better use this: https://stackoverflow.com/a/39266840/4031815

    Ok after some hours of research I found svg-android to be quite easy to use, so I'm leaving here step by step instructions:

    1. download lib from: https://code.google.com/p/svg-android/downloads/list Latest version at the moment of writing this is: svg-android-1.1.jar

    2. Put jar in lib dir.

    3. Save your *.svg file in res/drawable dir (In illustrator is as easy as pressing Save as and select svg)

    4. 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 boilerplate code like this

    Very easy I made a simple class to contain past code and reduce 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 accelaration 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);
    

提交回复
热议问题