Click here to Skip to main content
15,513,571 members
Articles / Mobile Apps / Android
Posted 25 Nov 2010


62 bookmarked

Android. ImageView with SVG Support

Rate me:
Please Sign up or sign in to vote.
4.83/5 (20 votes)
25 Nov 2010CPOL7 min read
The techniques to use SVG in the ImageView control


As you know, Android doesn’t support SVG format. But benefits of SVG are obvious. First, it’s scalable. You don’t need to have pictures in different resolutions, no need to scale, for example, bitmap image with a quality loss. SVG image can be scaled to any resolution and the quality will be the same. Second, SVG is an ordinary XML file, so its size can be much lesser than the raster format file of the same picture. Moreover, you can change a picture on the fly due to this feature. You can open an SVG file in an ordinary text editor and look how it's composed. And so on… But as Android doesn’t deal with SVG, it will imply some native coding. The good news is that there won’t be a lot of native coding. There are some open source libraries for parsing and rasterizing SVG format.


There are a lot of tutorials how to begin the native development for the Android platform, so I won’t repeat all of them here. I will just give some useful tips.

  • First, you need the Eclipse IDE. You can download it at [1].
  • Or as an alternative, you can use Motodev Studio [2]. I prefer the second one as it has some delicious features. BTW, you can install Motodev Studio as a plugin for the Eclipse IDE. I couldn’t setup it on OpenSUSE, but as the plugin it works fine.
  • Once Eclipse is installed, add CDT plugin to it.
  • Add Android plugin [3].
  • After that, add Eclipse Sequoyah[4] plugin needed for the native debugging. But make sure you installed CDT before Sequoyah. As the Sequoyah project claims, it installs all dependencies it didn’t really install CDT in my case. While installing Sequoyah, make sure you unchecked “Group Items by Category” and checked “Sequoyah Android Native Support”.
  • Also Windows users will need cygwin[5] (Add the Cygwin/bin path to your system.). While installing it, setup development tools.
  • Download Android SDK [6].
  • And at last, you will need Android NDK. Download CrystaX NDK[7]. It has support for C++ exceptions, RTTI and Standard C++ Library.
  • In Eclipse preferences, set Android SDK & NDK locations. That’s all for now.

First Approach

For the first approach, I will use android-libsvg [8] library. Really it depends on libsvg, libpng, libjpeg, libexpat and zlib. But at this moment, it has support for almost all features of SVG format. To get its sources, create android-libsvg folder somewhere in a file system and go to this folder in console (in cygwin for windows users) and run “bzr branch lp:libsvg-android” command. Bazaar will download sources to this folder.

The Beginning

Ok. Create a new Android project “ImageViewSvg”. Now right click on the project and go to AndroidTools/Add Native support. It will create “jni” folder in the project. Delete all stuff from it and copy contents of “jni” folder of android-libsvg project. Refresh jni folder in the project. Let’s look at file in “jni” folder. I'll explain some variables:

  • LOCAL_PATH := $(call my-dir) – my-dyr macro sets LOCAL_PATH variable used to locate source files into current directory
  • include $(CLEAR_VARS) – clears all local variables
  • LOCAL_MODULE – the name of the library
  • LOCAL_CFLAGS – sets compiler flags and some include directories
  • LIBJPEG_SOURCES, … - the list of sources files for each library that will be used
  • LOCAL_LDLIBS – links to additional libraries
  • LOCAL_SRC_FILES – the list of all source files to be compiled, here it contains all sources for all libraries
  • BUILD_SHARED_LIBRARY – link to mk file to build shared library

For more information, please see ANDROID-MK.TXT in NDK.

Sometimes on Windows, after restarting IDE, it can’t run ndk-build. Then right click the project and go to “Build Path/Configure Build Path” and change “Build command” to something like “bash /cygdrive/c/ndk/ndk-build”.

Next create com.toolkits.libsvgandroid package and copy there from the libsvg-android project. Preparations are over.

The ImageViewSvg Class

To make ImageView class to support SVG format, it’s enough to inherit from it and override some methods. But I want it to set standard android:src attribute as SVG file and to be able to pick the file from standard “drawable” folder vs. “raw” folder. At the beginning, let’s make all logic to be done in the constructor. To get access to the android:src attribute, add attrs.xml file to the res/values folder:

<?xml version="1.0" encoding="utf-8"?>
	<declare-styleable name="ImageViewSvg">
		<attr name="android:src"/>

Let’s look at ImageView class constructor sources. It contains the following code:

Drawable d = a.getDrawable(;
if (d != null) {

And look at setImageBitmap method. It just calls setImageDrawable. So we can use it in our constructor if we have the corresponding bitmap. But what about getting file from “drawable” folder. Nothing supernatural – get resource ID from the android:src attribute and read raw file into an input stream. Next, libandroidsvg gives us a way to parse SVG file:

So, the constructor will look like this:

public ImageViewSvg(Context context, AttributeSet attrs, int defStyle) {

		// Let's try load supported by ImageView formats
		super(context, attrs, defStyle);
        if(this.getDrawable() == null)
        	//  Get defined attributes
            TypedArray a = context.obtainStyledAttributes(attrs,
                    R.styleable.ImageViewSvg, defStyle, 0);
            // Getting a file name
            CharSequence cs = a.getText(R.styleable.ImageViewSvg_android_src);
            String file = cs.toString();
            // Is it SVG file?
            if (file.endsWith(".svg")) {
            	// Retrieve ID of the resource
                int id = a.getResourceId(R.styleable.ImageViewSvg_android_src, -1);
                if(id != -1){
               	try {
                		// Get the input stream for the raw resource
                		InputStream inStream = getResources().openRawResource(id);
                		int size = inStream.available();
                		// Read into the buffer
                		byte[] buffer = new byte[size];
						// And make a string
						mSvgContent = 
							(buffer, "UTF-8");
						// Parse it
            			mSvgId = SvgRaster.svgAndroidCreate();
					(mSvgId, mSvgContent.toString());
            			SvgRaster.svgAndroidSetAntialiasing(mSvgId, true);
            			mIsSvg = true;	

					} catch (IOException e) {
						mIsSvg = false;

Another problem is that SVG doesn’t have a size. It’s scalable and it’s all. Moreover ImageView layout parameters can be set to wrap_content, fill_parent or we can set predefined size of the image. But when a layout is required, Android sets the size and we can override onSizeChanged method. The only problem is wrap_content attribute. In this case, the size will be 0. The idea is to replace wrap_content with fill_parent on the fly. But doing it in the constructor will give nothing. If you debug through source codes, you will see that parent layout drags layout parameters from attributes directly and calls setLayoutParams method. Let’s override it:

public void setLayoutParams(ViewGroup.LayoutParams params){
		// replace WRAP_CONTENT if needed
		if(params.width == ViewGroup.LayoutParams.WRAP_CONTENT
				&& getSuggestedMinimumWidth() == 0)
			params.width = ViewGroup.LayoutParams.FILL_PARENT;
		if(params.height == ViewGroup.LayoutParams.WRAP_CONTENT
				&& getSuggestedMinimumHeight() == 0)
			params.height = ViewGroup.LayoutParams.FILL_PARENT;

And onSizeChanged:

public void onSizeChanged(int w, int h, int ow, int oh){
		//Create the bitmap to raster svg to
			Canvas canvas = new Canvas();
		mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
		// Render SVG with use of libandroidsvg
			mSvgId, canvas,
			0, 0, canvas.getWidth(), canvas.getHeight());	
		super.onSizeChanged(w, h, ow, oh);

And at last, it’s the time to try it. Create the following layout:

<?xml version="1.0" encoding="utf-8"?>
	<LinearLayout xmlns:android=""

And run:


Debugging Native Code

To debug native code, you can follow the instructions given by Carlos Souto at Sequoyah Project [9]. But during the first time, some things are unclear. So there are several tips:

  • While configuring C++ debug configuration, the application really must be app_process, don’t care Eclipse says the program doesn’t exist, it will be created later.
  • You should run ndk-gdb each time you run debugging. Sometimes the command should be ndk-gdb –adb=<path-to-sdk>/tools/adb –force.
  • Don’t forget to set "debuggable" in the manifest.

Second Approach. Anti Grain Geometry.

There is another library where you can use to rasterize SVG files. It’s Anti Grain Geometry[10]. The only extra library that will be needed is libexpat. We already have it in our project. In the jni folder, create folders like this:


Copy the corresponding files from agg sources folder into gpc/include/src folders. There in an examples folder where you can find svg_viewer folder. Copy all files except svg_test into aggsvg jni folder. It will parse and rasterize SVG with use of AGG. But it has only basic support for SVG and can’t parse complicated stuff. You should extend the parser by yourself. In aggsvg-android folder, create aggsvgandroid.cpp file. The example parses SVG from a file system. To parse a string, add the following method to a parser class:

void parser::parse(const char *chars, int length){

    	char msg[1024];

	    XML_Parser p = XML_ParserCreate(NULL);
	    if(p == 0)
		    throw exception("Couldn't allocate memory for parser");

	    XML_UseForeignDTD(p, true);

	    XML_SetUserData(p, this);
	    XML_SetElementHandler(p, start_element, end_element);
	    XML_SetCharacterDataHandler(p, content);

	    int done = 0;
	    std::string str = std::string(chars);
	    std::istringstream inputString(str);

            size_t len = inputString.readsome(m_buf, buf_size);
            done = len < buf_size;
            if(!XML_Parse(p, m_buf, len, done))
                    "%s at line %d\n",
                throw exception(msg);

        char* ts = m_title;
            if(*ts < ' ') *ts = ' ';

At the end of file, add section to build another library. It’s pretty simple. Just clear variables after the first library build and set them to build another library. And here is the class to rasterize with use of AGG:

class SvgRasterizer{
	agg::svg::path_renderer m_path;
    double m_min_x;
    double m_min_y;
    double m_max_x;
    double m_max_y;
    double m_x;
    double m_y;
    pix_format_e pixformat;
	agg::rendering_buffer m_rbuf_window;

	SvgRasterizer(pix_format_e format, uint32_t width, 
			uint32_t height, void *pixels) : \
		m_path(), \
		m_min_x(0.0), \
		m_min_y(0.0), \
		m_max_x(0.0), \
		m_max_y(0.0), \
		m_rbuf_window.attach((unsigned char*)pixels, width, height, 4*width);

	void parse_svg(const char* svg, int length){
		// Create parser
		agg::svg::parser p(m_path);
		// Parse SVG
		p.parse(svg, length);
		// Make all polygons CCW-oriented
		// Get bounds of the image defined in SVG
        m_path.bounding_rect(&m_min_x, &m_min_y, &m_max_x, &m_max_y);

	void rasterize_svg()
		typedef agg::pixfmt_rgba32 pixfmt;
		typedef agg::renderer_base<pixfmt> renderer_base;
		typedef agg::renderer_scanline_aa_solid<renderer_base> renderer_solid;

        pixfmt pixf(m_rbuf_window);
        renderer_base rb(pixf);
        renderer_solid ren(rb);

        agg::rasterizer_scanline_aa<> ras;
        agg::scanline_p8 sl;
        agg::trans_affine mtx;

        double scl;
        // Calculate the scale the image to fit given bitmap
        if(m_max_y > m_max_x)
        	scl = pixf.height()/m_max_y;
        	scl = pixf.width()/m_max_x;

        // Default gamma as is
        mtx *= agg::trans_affine_scaling(scl);


        // Render image
        m_path.render(ras, sl, ren, mtx, rb.clip_box(), 1.0);


And in sources, I’ve added an ability to test both approaches:



So, there are at last two ways to show SVG file in Android. The main benefit of libsvg-android is that it is ready to use, but it is more than three times slower than AGG, with which you should extend SVG parser by your own. Also with AGG, you get extra features for the image processing. I’ve just used ImageView in the layout, but to use it programmatically you, of cause, should override more methods, such as setImageResource for example.

That’s all. Thanks!




  • 25th November, 2010: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer
Russian Federation Russian Federation
• More than 10 years experience in software development
• 3 years experience in direction of automation department.
• software engineering: experience in the whole life cycle of software development
• languages: Kotlin, Swift,Objective-C, C++, C#, Java, ASP.NET, HTML, XML, JavaScript, Visual FoxPro, MS SQL, T-SQL
• Gathering, specification and the analysis of requirements of the customer to the software.
• The analysis of a subject area.
• Estimations of labour input of development.
And so on...

Comments and Discussions

SuggestionPlease update the project Pin
matheszabi-RO6-Oct-13 3:46
matheszabi-RO6-Oct-13 3:46 
QuestionErro on Windows Pin
Member 1001296629-Apr-13 6:58
Member 1001296629-Apr-13 6:58 
QuestionHow can write svg file in android? Pin
paragchauhan2010@gmail.com25-Sep-12 10:38
paragchauhan2010@gmail.com25-Sep-12 10:38 
AnswerRe: How can write svg file in android? Pin
Igor Kushnarev25-Sep-12 20:24
professionalIgor Kushnarev25-Sep-12 20:24 
GeneralRe: How can write svg file in android? Pin
paragchauhan2010@gmail.com26-Sep-12 9:44
paragchauhan2010@gmail.com26-Sep-12 9:44 
GeneralRe: How can write svg file in android? Pin
Igor Kushnarev26-Sep-12 19:39
professionalIgor Kushnarev26-Sep-12 19:39 
GeneralRe: How can write svg file in android? Pin
paragchauhan201026-Sep-12 21:11
paragchauhan201026-Sep-12 21:11 
QuestionSome issue with rotation Pin
varis15-Oct-11 18:20
varis15-Oct-11 18:20 
AnswerRe: Some issue with rotation Pin
Igor Kushnarev16-Oct-11 19:57
professionalIgor Kushnarev16-Oct-11 19:57 
QuestionError while trying your Examplecode Pin
t0mM3k12-Jul-11 23:54
t0mM3k12-Jul-11 23:54 
AnswerRe: Error while trying your Examplecode Pin
Igor Kushnarev13-Jul-11 6:06
professionalIgor Kushnarev13-Jul-11 6:06 
GeneralRe: Error while trying your Examplecode Pin
t0mM3k13-Jul-11 22:03
t0mM3k13-Jul-11 22:03 
GeneralRe: Error while trying your Examplecode Pin
Igor Kushnarev13-Jul-11 23:00
professionalIgor Kushnarev13-Jul-11 23:00 
AnswerRe: Error while trying your Examplecode Pin
Mirko Häberlin6-Mar-13 7:58
Mirko Häberlin6-Mar-13 7:58 
QuestionNeed a simple andriod app to create Gallery and load image Pin
SenthilKM14326-Jun-11 5:44
SenthilKM14326-Jun-11 5:44 
AnswerRe: Need a simple andriod app to create Gallery and load image Pin
Igor Kushnarev26-Jun-11 21:40
professionalIgor Kushnarev26-Jun-11 21:40 
QuestionDownload Source Pin
Aleh Krutsikau7-Jun-11 4:40
Aleh Krutsikau7-Jun-11 4:40 
AnswerRe: Download Source Pin
Igor Kushnarev11-Jun-11 4:05
professionalIgor Kushnarev11-Jun-11 4:05 
GeneralSVG that doesn't work Pin
feeder18035-Feb-11 1:51
feeder18035-Feb-11 1:51 
GeneralRe: SVG that doesn't work Pin
Igor Kushnarev7-Feb-11 1:40
professionalIgor Kushnarev7-Feb-11 1:40 
GeneralThank You for Your work! I've made some improvements. Pin
diov13-Dec-10 23:29
diov13-Dec-10 23:29 
GeneralRe: Thank You for Your work! I've made some improvements. Pin
Igor Kushnarev14-Dec-10 0:53
professionalIgor Kushnarev14-Dec-10 0:53 
GeneralMy vote Pin
Kodbar Ka26-Nov-10 5:23
Kodbar Ka26-Nov-10 5:23 
GeneralRe: My vote Pin
Igor Kushnarev26-Nov-10 7:26
professionalIgor Kushnarev26-Nov-10 7:26 
GeneralRe: My vote Pin
Igor Kushnarev28-Nov-10 23:29
professionalIgor Kushnarev28-Nov-10 23:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.