Friday, November 3, 2017

Displaying SVG image in Android application

SVG - a markup language for scalable vector graphics, is intended for describing two-dimensional vector graphics in XML format.. In this article, we will display a SVG image on the ImageView.


This format has many advantages (you can read in the Wiki(https://ru.wikipedia.org/wiki/SVG)). But using SVG in your project, you will see that:
- Now the development time of the application has decreased, since it is not necessary to cut a large number of images for different resolutions (at least for five: mdpi, hdpi, xhdpi, xxhdpi, xxxhdpi).
- In addition, the weight of the application is significantly reduced. For example, my application Snowy: Weight control weighs only 3.3 MB, and contains more than 50 different icons and images.

How to prepare SVG images for an Android project?

You can either draw vector images in a graphics editor that supports SVG (for example, Sketch), or download suitable icons. But, in order to use SVG in Android, the file must be converted to VectorDrawable.
To do this, you can use the following service: http://inloop.github.io/svg2android/
IMPORTANT: If you use complex shapes, rotations, flips, then when converting, you must tick "Bake transforms into path (experimental)"

How to work with SVG on Android?

1. All the converted xml images are placed in the folder res/drawable.

2. In gradle make the following changes:
android {
  defaultConfig {
    vectorDrawables.useSupportLibrary = true
  }
}
dependencies {
  compile 'com.android.support:appcompat-v7:27.0.0'
}
VectorDrawable support is available in the Android Support Library 23.2 and above, it is better to use the latest available version of the library (at the time of writing - 27.0.0)


3. Now just display our drawable in android.support.v7.widget.AppCompatImageView (instead of  ImageView), without forgetting to add in the root of the layout: xmlns:app="http://schemas.android.com/apk/res-auto":
<android.support.v7.widget.AppCompatImageView
      xmlns:app="http://schemas.android.com/apk/res-auto"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:srcCompat="@drawable/ic_new_releases_24px"/>

You can change the color of the image using the tint property:
      app:tint="@color/colorPrimary"


All described successfully implemented in my application Snowy: Weight Control. If it's not difficult for you, support the project with a good review and a positive rate! Thank you!

No comments:

Post a Comment