Android svg to vectordrawable

Android — Working with VectorDrawable…. can we easily convert SVG to VectorDrawable ?

Apr 6, 2016 · 4 min read

Introduction :
The main problem with a bitmap image in android is that we cannot scale it without losing its quality. That’s why we need to create different bitmap images for different screen devices. With api level 21 ( android 5.0) , google has introduced support for vectorDrawable. (only for devices api >= 5.0 but using appcompat v 23.2 , we can use on all devices running 2.1 and above .check this post of Chris Banes for more ).

VectorDrawable images are simply xml file that contains all information of an image (like lines, curves etc. ) and the color associated with each one of them. The biggest advantage of using vectorDrawable is that we need only one image for different screen devices.This not only reduces the size of the final apk, also it simplifies the maintenance of the project.

Many other platforms use vector images in SVG (Scalable Vector Graphics) format, but we cannot use SVG with android application. (yes…there are 3rd party libraries that we can use to work with SVG files )

Vector Asset Studio :
This tool was introduced with android studio 1.4 . Using this tool, we can convert SVG files to vectorDrawable and also we can use any material design vector assets provided by the software. Follow these steps to start Vector Asset Studio :

1. Open any project on Android Studio.
2. Right click on “res” -> new -> Vector asset
3. As you can see we can choose inbuilt material design icon files and also local svg files.

But VectorDrawable format supports a subset of SVG features and so it will not work for all SVG files. e.g. if SVG file is using Gradient , pattern fills or l ocal IRI reference , it will not work.

3rd Party Library :

Other 3rd party SVG to vectorDrawable converters are also available like svg2android ,but it has also the same restrictions. Recently this tool has added support for local IRI references . you must select the Bake transforms into path (experimental)option for this. SVG gradients and pattern fills are still not supported ,as VectorDrawable doesn’t support itself .

– Also, we can use SVG optimisation tool like svgomg to optimise a complex svg before converting it to a vectorDrawable using any of the method explained above.

Ok..so let’s check which one will be better for vector conversion. I am using this vector from freepik for this example.

  1. Download it and Extract the zip file

2. Only eps file is available.
3. We can convert it to svg file using online converter like cloudconvert
4. On Illustrator it looks like :

4.Next, I will try to convert it to vectorDrawable :

Using Android Studio :

1. File -> new ->Vector Asset -> click on Local SVG file and select the svg file.

Oops….seems like this vector file contains patterns . As we have mentioned above ,vectors with gradient , pattern and IRI reference are still not convertible.

Using svg2android tool :

  1. Drag and Drop the svg file on svg2android -> copy the generated xml code -> create one new drawable file and paste it

Pattern part is still not converted but, at least, all other parts are converted properly.

From the above image, it is clear that the “football” vector is causing the problem.

So if we want to convert any svg vector file to android vectorDrawable, svg2android is more helpful than vector studio . At least we can check which part can be convertible and which part is not.

I have tried it on “Android Studio 2.1 preview 3” , and since vector is now supported on pre-lollipop devices, hopefully, google will add some more features to Vector Studio in future.

Читайте также:  Android sms center number

Источник

Android working with SVG / vector drawables

While developing Android Applications, supporting multiple resolutions are sometime nightmare to developers. Including multiple images for different resolutions also increases the project size. The solution is to use Vector Graphics such as SVG images. While Android does not support SVGs (Scalable Vector Graphics) directly, with the launch of Lollipop a new class was introduced called VectorDrawable, which allows designers and developers to draw assets in a similar fashion using only code.

Simply explained, vector graphics are a way of describing graphical elements using geometric shapes. They are particularly well suited to graphical elements created in packages such as Adobe Illustrator or Inkscape where simple geometric shapes may be combined in to much more complex elements.

1. What is VectorDrawable?

As the name implies, vector drawables are based on vector graphics, as opposed to raster graphics, vector graphics are a way of describing graphical elements using geometric shapes. It is similar to a SVG file. In Android Vector Drawable are created as XML files. Now there is no need to create different size image for mdpi, hdpi, xhdpi, xxhdpi, xxxhdpi etc. We need only one vector file for multiple screen size devices. Also for older versions of Android that don’t support vector drawables, Vector Asset Studio can turn your vector drawables into different bitmap sizes for each screen density at runtime.

Here is the detailed information Vector Asset Studio.

Note: For this project I’m using gradle version 2.2, my suggession is to use 2.0+. However if you’re using gradle version below 2.0 then you’ll need to add some more code to the app level build.gradle file which I’ve mentioned below.

2. Creating Android Project

1. Create a new project in Android Studio from File ⇒ New Project and fill the project details.

2. Open build.gradle in app module, add the below line inside defaultConfig block.

So the complete build.gradle looks like

If you are using gradle version below 2.0 then use following

2.1 Creating VectorDrawable from Material Icons.

So let us start by creating VectorDrawables from Material Icons (Material Icons are the official icon set from Google that are designed under the material design guidelines, these icons are open source and are beautifully crafted, delightful, and easy to use in your web, Android, and iOS projects).

3. In the project Right click on the drawable directory

4. Go to New ⇒ Vector Asset

5. Click on the launcher icon to browse Material Icons

6. Select an icon and click on ok

7. Review the name of the file then click on next.

8. Now Vector Asset Studio will show the location about where the file is being saved, review it and click on finish.

9. The drawable folder will now consist of a newly created file (In my case ic_flight_takeoff)

below is the file code –

You can modify the width and height of the vector as per your requirement (by default it stays as 24dp), a vector may consist of one or more paths. A path may have many attributes among which fillColor and pathData are the most important. fillColor attribute defines the color of the path, it must be a color attribute (hash code in #aarrggbb, or may also point to a color resource). pathData defines the path shape. In this case I’ve modified the vector width, height and path fillColor.

2.2 Creating VectorDrawable from SVG or PSD

Now we have created vectorDrawable from Material Icon, what if we want a separate icon? We can create it from SVG or PSD, below are the procedure, but it also has some restrictions you can check out here – https://developer.android.com/studio/write/vector-asset-studio.html#PSD (though the restriction listed here for PSD, it applies to SVG also).

10. In the project Right click on the drawable directory

11. Go to New ⇒ Vector Asset

12. Click on the radio button saying “Local File (SVG, PSD)”

13. Click on the browse icon and navigate to your SVG or PSD file to select it

14. After selecting click ok

Читайте также:  Что можно остановить андроид

15. Verify the image in preview and click Next ⇒ Finish.

below is the file code generated from svg

3. Using VectorDrawable

We have successfully added VectorDrawables to the project, now it’s time to use them.

16. Open the layout file of main activity (activity_main.xml) and add the below xml. This layout contains shows how to use VectorDrawable with ImageView and other Views (as background) which is explained later in this tutorial.

The above layout generates a screen something like this.

3.1 Using VectorDrawable with ImageView from xml

So let us start with a simple ImageView, and even simpler by assigning the VectorDrawable to the ImageView through xml layout.

As you can see, we used app:srcCompat instead of android:src, so that the support library can do the rest to display the image seamlessly on all versions of android. (The support library converts VectorDrawables to raster graphics automatically on android versions below 5.0 – API 21, details are here). So it was that easy.

3.2 Using VectorDrawable with ImageView from Java

Now Let us do the same thing with Java code, i.e. assigning VectorDrawable to ImageView through Java Code.

17. Add another Vector Drawable (name it ic_android.xml) with the steps mention in section 2.1 or 2.2, you can also create a file with that name and paste the below code.

18. Open MainActivity.java and paste the below code.

Now, let me explain the code line by line.

19. For using VectorDrawable from java or to use it as background (in xml also) you need to intimate AppCompatDelegate to enable compat vector from resource. Below is the code for that.

20. Whenever you are going to use VectorDrawable from java or to use it as background (in xml also) remember to use AppCompatView instead of normal view, here I have used AppCompatImageView, please also refer to the layout we created before.

21. Now assign the VectorDrawable as src or background as you do it normally, AppCompat will take care of the rest.

22. We have added some flavors to it, We implemented OnClickListener on the ImageView to set random color filter on it, upon click.

3.3 Using VectorDrawable as Drawable with TextView

You may want to use VectorDrawable as background or as compound drawable with TextView, so below is an example.

As you can see from above code we have used a VectorDrawable in the drawableLeft attribute of android.support.v7.widget.AppCompatTextView, we can also do it from the java code using AppCompatTextView#setCompoundDrawables .

3.4 Using VectorDrawable to Customise RadioButton

So far the use was straightforward, what if you want to customise a RadioButton or CheckBox while using VectorDrawable? Now lets see that. If you go through the layout we created, once again then you can find that a RadioGroup which contains a series of AppCompatRadioButton, all the AppCompatRadioButtons there uses @drawable/radio_selector as background, below is the code for that.

As you can see this is a selector drawable as usual, the only difference is that it refers to VectorDrawables (vector image resources) instead of raster image resources. The remaining is taken care by android.support.v7.widget.AppCompatRadioButton itself as mentioned earlier (remember to use AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) for that also, even if you don’t consider backward compatibility).

The final output looks something like this.

I hope this article gave you a very good overview about Using Vector Drawables in Android. Feel free to ask any queries / doubts in comments section below.

Rivu Chakraborty is a Sr. Tech. Member of Institution of Engineers(India), Diploma holder Engineer in Computer Science. He is presently at MaxMobility Pvt. Ltd. as a Sr. Software Engineer (Android)

Источник

Vector Graphics in Android: Converting SVG to VectorDrawable

Vector graphics native support has long been on the wishlist of Android developers who have to export their vector graphics as a rasterized PNG file for each different device resolution.

Introducing VectorDrawable

The good news is that the Android SDK now has native support for basic vector graphic definitions. With the release of API 21 (Android 5.0) came VectorDrawable.

The most important things to understand if you want to implement drawables in your app using VectorDrawable are:

  • VectorDrawable is not implemented in the support library, therefore it will only work in Android 5.0+ (VectorDrawable support for older APIs may be coming soon to the support library)
  • VectorDrawable supports paths using the same definition as the ‘d’ attribute in the SVG format
  • VectorDrawable does not read or support the SVG format
  • VectorDrawable does not support gradients and patterns
  • VectorDrawable does not support numbers using scientific E notation (as commonly used in SVG)
Читайте также:  Android как посмотреть заблокированные номера

While it is important to understand that the SVG format is not supported, it doesn’t necessarily mean you can’t convert your existing simple SVG files. A VectorDrawable is specified through XML, with the format of the path data in the VectorDrawable using the same format as the specification for SVG paths. This allows us to reformat the XML in some SVG files to convert it into a VectorDrawable XML file.

If you are looking to use SVG files directly in your Android app take a look at this comparison of 3rd party solutions:

Case Study: Converting SVG to VectorDrawable

The penguin in the image below (Attribution: Larry Ewing) has been rendered from a SVG image. SVG images such as this can not be converted into a VectorDrawable as it uses LinearGradient in the original source.

Below is a rendered image of the flag of Ghana, it is also rendered from an SVG however as this image doesn’t have a gradient and only includes simple shapes, it is most suitable for conversion to a VectorDrawable. We will use this image as to illustrate how to convert an SVG into a VectorDrawable.

SVG Images are described using the XML format. The above image contains 4 elements; three stripes and a star. The SVG XML source may appear as follows:

If we want to create this same image as an Android VectorDrawable the first thing we need to do is ensure all items are described using paths. Remember only paths are supported in VectorDrawable. To do this we convert each rect definition in the SVG image to use a path definition. The following XML shows the new path objects:

The next step is to convert the XML into Android’s new VectorDrawable format. To do this we need to keep the path and color definitions but replace the formatting. The XML should now look like this:

This VectorDrawable file should be named with an .xml extension and placed in your drawables folder so it can be accessed in your Java source code or layout definition as you would with any other drawable.

The good news is you don’t need to step through this process by hand each time, there are tools to help you out. I have documented this process as it is important to know what and how to hand code the xml format as the conversion tools will not work all of the time so you may need to tweak the code from time to time.

To convert your SVG file to use only paths you can use Inkscape (The awesome open source SVG tool). Open the SVG file in Inkscape and select all items you want to convert to a path. Then from the Path menu select Object to path. If you use Adobe Illustrator then you need to convert the shapes into compound paths before saving the SVG.

To automate the conversion of an SVG file to the VectorDrawable format you can use the on-line open source svg2android tool.

VectorDrawable support pre Android 5.0

While the VectorDrawable class is only available on 5.0+ at this stage, an unofficial project has released support for older versions of Android.

Visit Mr. Vector on GitHub for the source code and usage instructions. You should note that the Vector XML used in this project is slightly different to the standard VectorDrawable specification. You can convert your simple SVG files to the Mr. Vector format using Svg2MrVector.

UPDATE MAY 2015: VectorDrawableCompat is in the process of being developed and may be added to the official support library. Once released there is no need to use the Mr. Vector project anymore, so keep an eye on the official Android Developers Blog for updates to the support library.

Источник

Оцените статью