Using SVG as a resource of image view in Android

Viewed 1288

I'm having trouble using an SVG file a source file for an imageView. I'm building an app with thousands of SVG drawing. it works when i save them in the drawable folder, but i don't want to end up with a huge APK. When I download them from a server as a file i can't set them as a source for the Image view (i try to to do something similiar to this, but with SVG)

Bitmap temp = BitmapFactory.decodeFile("file path");
        centerImage.setImageBitmap(temp);

but with an SVG file (that is saved as XML). I looked all over Stackoverflow but the only solution I saw was to save it as resources, which i prefer to avoid.

3 Answers

How I solved it in the end (with help from Amir MB): I have the SVG downloaded as a file from the server, that how i used the file so put them in an ImageView:

//file arrives from server
try{
    fileInputStream = new FileInputStream(file);
                    try {
                        Bitmap bitmap = Bitmap.createBitmap(dummyImage.getWidth(),dummyImage.getHeight(), Bitmap.Config.ARGB_8888);
                        canvas = new Canvas(bitmap);
                        SVG svg = SVG.getFromInputStream(fileInputStream);
                        svg.setDocumentHeight(dummyImage.getWidth());
                        svg.setDocumentWidth(dummyImage.getHeight());
                        svg.renderToCanvas(canvas);
                        dummyImage.setImageBitmap(bitmap);
                    }catch(SVGParseException S){
                        S.printStackTrace();
                    }
}catch(IOException e) {
                    e.printStackTrace();
                }

You can get the SVG from an input stream (probably in an AsyncTask) and convert it to a Drawable:

SVG svg = SVGParser.getSVGFromInputStream(inputStream);
Drawable drawable = svg.createPictureDrawable();
centerImage.setLayerType(View.LAYER_TYPE_SOFTWARE, null); //turnnig on software rendering
centerImage.setImageDrawable(drawable);

You could alternatively turn on software rendering in XML as well:

android:layerType="software"
Related