How to draw a SVG in Android Canvas

In this android programming source code example, we are going to draw a SVG in Android Canvas.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to draw a SVG in Android Canvas.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

</RelativeLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.media.Image;
import android.os.Bundle;
import android.widget.ImageView;

import com.caverock.androidsvg.SVG;
import com.caverock.androidsvg.SVGParseException;

public class CanvasActivity6 extends AppCompatActivity {
    private ImageView img;
    private SVG svg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_canvas6);
        img = (ImageView) findViewById(R.id.image);
        try {
            svg = SVG.getFromResource(getResources(), R.raw.androidlogo);
        } catch (SVGParseException e) {
            e.printStackTrace();
        }
        if(svg.getDocumentWidth() != - 1F) {
            svg.setDocumentHeight(600f);
            svg.setDocumentWidth(600f);
            Bitmap bitmap = Bitmap.createBitmap(700, 700, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawARGB(0, 255, 255, 255);
            svg.renderToCanvas(canvas);
            img.setBackground(new BitmapDrawable(getResources(), bitmap));
        }
    }
}

app/build.gradle

implementation 'com.caverock:androidsvg-aar:1.4'

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment