📜 ⬆️ ⬇️

Vector Drawable API. Application possibilities

2014 was a special year for those involved in Android development - it brought one of the most significant Android updates in its history, Android 5.0 version. With this update we received a new visual language, detailed guidelines, many new APIs and tools. And, as always in the case of such massive updates, not all innovations immediately make their way into real projects. Somewhere the inertia of thinking of developers who are used to solving certain tasks in a certain way, somewhere - the lack of documentation on the new API, somewhere - the lack of support for new features on older versions of the platform. But time does not stand still and thanks to the work of the Android team, as well as independent developers, such APIs are gradually gaining backward support. And today I want to talk about the Android Vector Graphics API, which can seriously ease the life of a developer, but is still not popular.

vector android



')
Little materiel
Computer graphics operates with two types of files - raster and vector. Raster files are a set of matrices, each cell in which describes one section of the image, one of its pixels. Vector files contain a set of primitive figures and commands that allow one or another form to be constructed according to given coordinates. Differences in the internal structure of raster and vector graphics files are reflected in the behavior of various types of computer graphics under different usage scenarios. So raster files are very poorly scaled, especially in a big way - in the source file there is simply no information to fill the image of a larger area. Also, in raster formats there is a direct relationship between the physical size of the image and the size of the file on disk. In turn, an object in a vector format file can have only one fill, so in order to create a photorealistic image, you need to create many objects to display highlights, shadows, textures, which, firstly, takes great pains to the illustrator, and secondly, it puts a load on the device rendering.
It is not surprising that in the 30 years of the existence of desktop publishing systems, a kind of “division of labor” has arisen, when raster formats are used for photo images, and vector ones for simple graphics, fonts, logos.


Material Design and Vector Graphics


How can we use the support of vector graphics, which appeared with the release of Android 5.0? To answer this question, it is necessary to consider Material Design not just as a new Android design style, but as part of a more general trend in interface design, which began with the release of the Metro interface in Windows 8. Then there was Flat Design in iOS 7 and Material Design in Android The key characteristics of this style, the origins of which can be found in the works of representatives of the Bauhaus school, as well as in the direction of the so-called. the Swiss school of typography are the abandonment of skephomorphism, the use of simple and expressive colors, a clear structure layout.

icon comparison


This allows you to get rid of the use of a huge number of photographic textures, to switch to using simple vector graphics in the interface. Just look at the Material Design iconography to make sure that in the icons there is no place for photo-realistic three-dimensionality, glare and gradients, the icon in Material Design is an expressive figure with clear borders and a flat fill. Thanks to this, we can use vector graphics for icons.

material icons

Switching to the vector image format gives us a number of advantages: we don’t need to cut a set of icons for all screen resolutions, don’t need to cut it again in case of any changes, we also need to note the reduction in the size of the installation package with the application, as well as the decrease in the load on the RAM required to download textures and icons in png. Some time ago, an article appeared in the technical blog Instagram where service engineers described the process of redesigning an application on Material Design guides. According to their data, the transition to Material Design and the accompanying “flattening of the interface” made it possible to reduce the launch time of the application by 120 ms.
Hopefully, after such arguments, you wanted to use vector graphics and now I will move on to a detailed analysis of the API structure and methods of working with it.

VectorDrawable class


Vector tag

The basis of the vector graphics API in Android is the VectorDrawable class. Objects of this class are resources and are described using the XML language, they are placed in the res/drawable our project. The root element of the class is the vector tag. The vector tag has several attributes, two groups of attributes are required, which determine the size of our drawable . I'm talking about the width and height attributes — they are specified using some units of measurement (their standard set for Android is dp , sp and px ), as well as viewportWidth and viewportHeight — they are specified without units. With the help of width and height we can specify the physical size that our drawable will take on the screen, and the viewport can be compared with the window through which we look at our image. viewport sizes can be the same or different from the image size. At the same time, by changing the size of the viewport , we can change the area occupied by the figure inside the drawable .

viewport comparison

It is worth noting that viewport does not have the ability to set pivotPoint coordinates and resizing the viewport will be counted from the upper left corner. Also, the vector element has a number of other attributes, the meaning of which is clear from the name.

 <vector android:name android:tint android:tintMode android:autoMirrored android:alpha> <vector/> 


Path element

The main thing that no VectorDrawable file can do without is the Path tag. The most important attribute for the Path element is the pathData attribute. Its value is a string of characters separated by commas. These characters are nothing but SVG format commands.

 <path android:pathData="M141.4,188.2H51V329c0,15.4,16.4,15.5,16.4, 15.5l20.8,0v19.7h0c0,0.3,0,0.5,0,0.8c0,11,8.9,19.9,19.9,19.9c11, 0,19.9-8.9,19.9-19.9c0-0.3,0-0.5,0-0.8h0v-19.7l13.4,0l13.4,0v19.7h0c0, 0.3,0,0.5,0,0.8c0,11,8.9,19.9,19.9,19.9c11,0,19.9-8.9,19.9-19.9c0-0.3, 0-0.5,0-0.8h0v-19.7l20.8,0c0,0,16.4,0,16.4-15.5V188.2H141.4z"/> 


SVG is a vector graphics format designed specifically for the Internet, and it is supported by all modern browsers, and export to SVG is available from most graphic editors. SVG supports a set of primitive shapes, such as an oval, rectangle, spiral, etc., as well as arbitrary shapes. Arbitrary shapes are described using a set of commands that represent the coordinates of points and straight lines, Bezier curves and arcs connecting them. Having executed these commands successively, it is possible to build the figure we need.
Since XML is also used to describe SVG files, we can open it in a text editor and find the Path object. This object will have an attribute d , the value of which will be a string with commands identical to those that we can find as the value of the pathData attribute of the pathData object in the VectorDrawable resource. This circumstance allows us to easily create VectorDrawable resources — to do this, simply copy the command set from an SVG file to our VectorDrawable resource.

  <path id="shapePath1" d="M229.1,174.2 C226.2,165.5 222.1,157.5 216.9,150.3 C208.4,138.3 197.6,129.5 184.7,123.6 L202.4,98.5 C202.6,98.2 202.7,98 202.7,97.5 C202.7,96.8 202.3,96.2 201.4,95.7 C200.6,95.1 199.8,94.9 199.2,95.1 L198.4,95.6 L180.1,121.7 C168.8,117.5 156,115.2 141.6,115.2 C127.4,115.2 114.7,117.2 103.6,121.4 L85.5,95.5 L84.7,95 C84.1,94.9 83.3,95 82.5,95.6 C81.6,96.1 81.2,96.7 81.2,97.4 C81.2,97.9 81.3,98.1 81.5,98.4 L98.9,123 C85.8,128.7 74.8,137.7 66.2,149.8 C60.9,157 56.8,165 53.8,173.7 C52.5,177.5 51.7,180.8 51.2,183.5 L231.9,183.5 C231.3,181 230.4,177.9 229.1,174.2 Z" /> 


In order for us to see our shape, we need to assign a fill to it and, optionally, a stroke. This is done using the attributes fillColor, strokeColor, strokeWidth. It should be noted that, unlike SVG, a figure in VectorDrawable cannot have a gradient fill - only a certain color.

 <path android:pathData android:fillColor, android:fillAlpha android:strokeColor, android:strokeWidth, android:strokeAlpha android:trimPathStart, android:trimPathEnd, android:trimPathOffset android:strokeLineCap, android:strokeLineJoin, android:strokeMiterLimit /> 


Group element

The simplest vector file contains only one shape, but in complex images the number of such shapes can amount to dozens. For convenience of working with them, individual figures can be grouped together using the Group element. The ability to combine several Path objects into a group allows not only to organize the structure of our drawable-resource, but also gives the opportunity to apply group settings to a set of objects, but most importantly, the group can be used for animation, which will be discussed later.
Thus, in one VectorDrawable resource, we can create complex graphics using various Path objects, which can be used to define our own color, transparency, stroke, and indicate the position on the screen. Path objects can be combined into groups, for which, again, you can specify a number of group attributes. The most interesting is that all attributes can be zanimirovat, while to apply one animation to a set of Path objects, it is convenient to combine these objects into a group.

 <group android:name android:rotation android:pivotX, pivotY android:scaleX, scaleY android:translateX, translateY> <group/> 


Class AnimatedVectorDrawable


The second part of the vector graphics API, which appeared in Android Lollipop, is the AnimatedVectorDrawable class, which allows you to create animations for the VectorDrawable classes. AnimatedVectorDrawable is a PropertyAnimation extension that allows us to create animations based on changing the values ​​of any object attributes. AnimatedVectorDrawable files also belong to application resources and are created using XML. The root element of a vector animation resource is the animated - vector tag. This tag has only one drawable attribute in which we specify the name of the VectorDrawable resource for which we want to create an animation. Inside the animated-vector element are target objects that are targets for animations. The most remarkable is that the animated-vector can contain more than one target . This fact makes it possible to create complex animations, allowing you to animate different parts of the image with different animations, creating complex animations.

 <animated-vector android:drawable="@drawable/vector_drawable"> <target android:name="head" android:animation="@anim/headAnimation" /> <target android:animation="@anim/eyes_anim" android:name="eyes"/> </animated-vector> 


In particular, the famous hamburger-to-arrow animation, which so fascinated everyone at the time of the announcement of Android 5.0, is easily created using vector animation: the upper and lower bars of the hamburger move towards the middle, at the same time the whole group rotates 180 ° - here we specify three target and create three animations for them.

animation examples


The target element has two main attributes — name , in which we specify the name of the Path object or the Group object to be animated, and animation , where we send a link to the animation resource located in the res/anim folder.

 <set> <objectAnimator android:duration="400" android:propertyName="pathData" android:valueType="pathType" android:valueFrom="@string/pathFrom" android:valueTo="@string/pathTo" /> </set> 


An animation resource is a standard animator-set , with an objectAnimator object inside. As the value of the propertyName attribute, we can specify any attribute of the Path or Group object from VectorDrawable. Depending on the attribute type, we must specify the corresponding value type in the valueType attribute.
Android Lollipop with the advent of a new type of graphics brought a new type of property , for which you can create an animation - an animation of the value of the pathData attribute of the Path object. To do this, a new pathData value appeared in the propertyName field and the corresponding valueType value, valueType , pathType . In this case, the old fields valueFrom and valueTo take as arguments two strings with sets of commands describing the initial and final shape of the figure, respectively. Thanks to this new type of animations, you can create complex animations that transform the shape of a shape that was previously unavailable in Android — for example, morphing animations, which transform the Play button into the Pause button. Google itself recommends saving data with path commands in string resources.
It is worth noting that in order for an animation to work successfully, the number of commands and the type of commands in the source and destination path must be the same. Otherwise, you will get a runtime exception. This severe condition at one time took me a lot of time, but recently the VectAlign tool appeared , allowing you to automatically align two lines with paths according to the number and type of commands.

Running animation


Vector animation files implement the Animatable interface and to start the animation, we request the Drawable , bring it to the Animatable and call the start() method.

 ((Animatable) imageView.getBackground()).start(); 

Animatable interface Animatable extremely simple - there are only three methods: isRunning() , start() , stop() . Thus, there is no possibility of setting the AnimationListener . Also there is no possibility to transfer our vector animation to AnimatorSet . Therefore, the direct ability to create a choreography of animations, or run some actions to complete the animation is missing. More precisely, it was absent - in version 23 of the Android SDK, the Animatable interface was expanded with the new Animatable2 interface, which allows AnimationCallback to be recorded for our vector animation.
For versions up to 23 for choreography, you can use the delayed launch feature, for example, using the Handler.postDelayed() method.

Back support


Returning to what I started with, I want to remind you that the introduction of vector graphics in projects so far has been hampered by the lack of reverse support for this functionality on Android versions <5.0. However, time does not stand still and, although there is no official support for vector formats on older versions of the platform, thanks to independent developers, libraries appear that allow using VectorDrawable on devices with API> = 14. And I’m talking about VectorCompat and BetterVectorDrawable libraries . I myself have experience only with the VectorCompat library, so I will only talk about it. Those interested in the intricacies of working with BetterVectorDrawable refer to a series of astudent articles: part 1 , part 2 ;
In order for resources with vector graphics to work through the backward-compatible library, we need to fulfill a number of conditions. First, in the XML resources that describe our VectorDrawable and animations for them, you must duplicate a number of attributes, such as viewportHeight, viewportWidth, fillColor, pathData, valueType with the namespace of the VectorCompat library.
Another limitation is expressed in the fact that we cannot VectorDrawable directly specify how the background for the view in the XML resource layout. To use VectorDrawable, we need to load it from the XML resource in the java-code and already there indicate it as a background for the ImageView.
The library offers three methods for loading VectorDrawable from XML: VectorDrawable.getDrawable(), AnimatedVectorDrawable.getDrawable() and ResourcesCompat.getDrawable() . The third method is preferable for two reasons: firstly, when using it, there is no difference which class object we are trying to load - VectorDrawable or AnimatedVectorDrawable, and secondly, on devices with Lollipop and higher, it will automatically use the native method from the Android SDK.
Otherwise, there are no other features of using vector animation using the VectorCompat library.

Preparation of vector files


In conclusion, it is necessary to discuss the theme of preparing vector graphics files for Android. Exporting to SVG is supported by most vector editors, including Corel Draw, Adobe Illustrator, and Sketch. However, when using Adobe Illustrator, there is a problem with positioning the image relative to the viewPort - despite the fact that when viewed in Illustrator, the image is centered relative to the viewPort , when you open the exported SVG file, for example, in the browser, it is shifted to the side. Therefore, to use SVG files from Illustrator, they must first be saved in another program, for example, free Inkscape .
At the same time, you shouldn’t forget that of the entire SVG set, Android only supports Path objects. Therefore, primitive figures, it is necessary to transform on the way. In Sketch, this is done with the command Layer> Paths> Vectorize stroke, and in Illustrator> Object> Expand.
Having the SVG file available, we can open it in a text editor and find the tag . , d — . , pathData VectorDrawable.
, Android Studio , . 1.4 Vector Asset Studio — SVG Vector Drawable SVG . res/drawable File > New > Vector Asset.

vector asset studio

1.4 Preview SVG Illustrator. ( ) 21. Material Design. SVG , , . 1,4 Android Gradle png- .
SVG , Android . png , apk-. vector!

Rambler.Android , 10 .
, ,

animated droid
. , d — . , pathData VectorDrawable.
, Android Studio , . 1.4 Vector Asset Studio — SVG Vector Drawable SVG . res/drawable File > New > Vector Asset.

vector asset studio

1.4 Preview SVG Illustrator. ( ) 21. Material Design. SVG , , . 1,4 Android Gradle png- .
SVG , Android . png , apk-. vector!

Rambler.Android , 10 .
, ,

animated droid
. , d — . , pathData VectorDrawable.
, Android Studio , . 1.4 Vector Asset Studio — SVG Vector Drawable SVG . res/drawable File > New > Vector Asset.

vector asset studio

1.4 Preview SVG Illustrator. ( ) 21. Material Design. SVG , , . 1,4 Android Gradle png- .
SVG , Android . png , apk-. vector!

Rambler.Android , 10 .
, ,

animated droid
. , d — . , pathData VectorDrawable.
, Android Studio , . 1.4 Vector Asset Studio — SVG Vector Drawable SVG . res/drawable File > New > Vector Asset.

vector asset studio

1.4 Preview SVG Illustrator. ( ) 21. Material Design. SVG , , . 1,4 Android Gradle png- .
SVG , Android . png , apk-. vector!

Rambler.Android , 10 .
, ,

animated droid
. , d — . , pathData VectorDrawable.
, Android Studio , . 1.4 Vector Asset Studio — SVG Vector Drawable SVG . res/drawable File > New > Vector Asset.

vector asset studio

1.4 Preview SVG Illustrator. ( ) 21. Material Design. SVG , , . 1,4 Android Gradle png- .
SVG , Android . png , apk-. vector!

Rambler.Android , 10 .
, ,

animated droid

Source: https://habr.com/ru/post/267073/


All Articles