- Adding Vector Assets in Android Studio
- Using vector assets in Android apps
- Understanding Android’s vector image format: VectorDrawable
- Android devices come in all sizes, shapes and screen densities. That’s why I’m a huge fan of using resolution…
- Draw a Path: Rendering Android VectorDrawables
- In the previous article, we looked at Android’s VectorDrawable format, going into its benefits and capabilities.
- AndroidX First
- 1. Enable Support
- 2. Load with AndroidX
- In Practice
- Views without compat attributes
- Nested d rawable s
- Out of process loading
- X Marks the Spot
- How to Add Vector Assets in Android Studio?
- How Vector Asset is different from Image Asset?
- Problem using PNG’s
- Bitmap vs Vector
- Benefits of Vector Assets
- How do vector assets render?
- Vector Formats
- Step by Step Implementation
Adding Vector Assets in Android Studio
In the previous lesson, you added a menu item to your toolbar. In this lesson, you’ll learn how to add an icon for a menu item.
Right-click the res > drawable folder in the Explorer area on the left of Android Studio. From the menu that appears, select New > Vector Asset:
When you click on Vector Asset, you’ll see the Configure Vector Asset dialogue box appear in earlier versions of Android Studio:
In later versions, you’ll see this dialog box:
Notice the highlighted button in the image above. Click this button, either Icon or Clip Art, to see lots of icons you can choose from:
Select an icon that reflects what your menu item will do. We’ve gone for a smiley-face for our favourites menu item:
Although the Size says 24dp by 24dp, you can change this. Select the Override checkbox and the size text boxes will activate. Type a new size for your icon. We’ll leave ours on 24, though.
Click the Next button to see what folder your icon is going in to:
Now click the Finish button to add the image to your drawable folder.
You can now use this drawable as an icon for your toolbar.
With your favourites_page menu item still selected, click on the icon property. Click the Pick a Resource button again to bring up the Resources dialogue box. You should see your new icon there, in the drawable section:
Click OK and your properties area should look like this:
If you want to change the colour of a Vector Asset, double click the XML file in the drawable folder (not the ic_launcher ones). You should see something like this:
A vector image is one built with paths. The path data connects series of points. Contrast this with a bitmap where images are built from a series of dots on a grid. So you can’t change the path data without change the image. But you can change the fill colours.
For the smiley-face we’ve chosen the first two paths in the XML file are for the eyes. The third set of points are for the mouth and the circle. (There is no fill for the background.) You can change the hexadecimal values from #000000 to anything you like. Click the black colour squares in the margins to bring up a colour dialogue box. Select some new colour for your vector shape.
You’re not quite ready to test it out, though, as the icon won’t show until we add some code later.
Let’s add two more menu items. Try to do these two yourself.
Add a new menu item to your layout. Change the ID to web_page. Set the title for your web string resource via the Resources dialogue box. Set the showAsAction to ifRoom. Add a new Vector Asset to your drawable folder, choosing any icon you like. Set the icon property to your new drawable. Your Properties area might then look something like this:
And your layout might look like this:
Add a third menu item to your layout. Change the ID to settings. Set the title to your settings_page string resource via the Resources dialogue box. Set the showAsAction to never. Because this menu item will never appear on the toolbar, you don’t need an icon. Your Properties area might then look something like this:
Your layout will look something like this one:
Now that we have all our menu items in place, we can switch to the Java code. We’ll start that in the next lesson below.
Источник
Using vector assets in Android apps
In previous posts we’ve looked at Android’s VectorDrawable image format and what it can do:
Understanding Android’s vector image format: VectorDrawable
Android devices come in all sizes, shapes and screen densities. That’s why I’m a huge fan of using resolution…
Draw a Path: Rendering Android VectorDrawables
In the previous article, we looked at Android’s VectorDrawable format, going into its benefits and capabilities.
In this post we’ll dive into how to use them in your apps. VectorDrawable was introduced in Lollipop (API 21) and is also available in AndroidX (as VectorDrawableCompat ) bringing support all the way back to API 14 (over 99% of devices). This post will outline advice for actually using VectorDrawable s in your apps.
AndroidX First
From Lollipop onward, you can use VectorDrawable s anywhere you would use other drawable types (referring to them using the standard @drawable/foo syntax) but I would instead recommend to always use the AndroidX implementation. This obviously increases the range of platforms you can use them on but more than this, it enables backporting of features and bug fixes to older platforms too. For example, using VectorDrawableCompat from AndroidX enables:
- Both nonZero and evenOdd path fillTypes —the two common ways of defining the inside of a shape, often used in SVGs ( evenOdd added to platform impl in API 24)
- Gradient & ColorStateList fills/strokes (added to platform impl in API 24)
- Bug fixes
In fact, AndroidX will use the compat implementation even on some platforms where a native implementation exists (currently APIs 21–23) to deliver the above benefits. Otherwise it delegates to the platform implementation, so still receives any improvements on newer releases (for example VectorDrawable was re-implemented in C in API 24 for increased performance).
For these reasons you should always use AndroidX, even if you’re fortunate enough to have a minSdkVersion of 24. There’s little downside and if/when VectorDrawable is extended with new capabilities in the future and they’re also added to AndroidX, then they’ll be available straight away without having to revisit your code.
To use the AndroidX vector support, there are 2 things that you need to do:
1. Enable Support
You need to opt in to AndroidX vector support in your app’s build.gradle :
This flag prevents the Android Gradle Plugin from generating PNG versions of your vector assets if your minSdkVersion is versions resources. That means if you declare a VectorDrawable in res/drawable/ it will move it to res/drawable-v21/ for you as it knows this is when the VectorDrawable class was introduced.
This prevents attribute ID clashes — the attributes you use in VectorDrawable s ( android:pathData , android:fillColor etc) each have an integer ID associated with them, which were added in API 21. On older versions of Android, there was nothing preventing OEMs from using any ‘unclaimed’ IDs, making it unsafe to use a newer attribute on an older platform.
This versioning would prevent the asset from being accessed on older platforms, making a backport impossible—the gradle flag disables this versioning for vector drawables. This is why you use android:pathData etc within your vectors rather than having to switch to app:pathData etc like other backported functionality.
2. Load with AndroidX
When loading drawables you need to use methods from AndroidX which provide the backported vector support. The entry point for this is to always load drawables with AppCompatResources.getDrawable . While there are a number of ways to load drawables (because reasons), you must use AppCompatResources if you want to use compat vectors. If you fail to do this, then you won’t hook into the AndroidX code path and your app might crash when trying to use any features not supported by the platform you’re running on.
VectorDrawableCompat also offers a create method. I’d recommend always using AppCompatResources instead as this adds a layer of caching.
If you want to set drawables declaratively (i.e. in your layouts) then appcompat offers a number of *Compat attributes that you should use instead of the standard platform ones:
- Don’t: android:button
- Do: app:buttonCompat
- Don’t: android:drawableStart android:drawableTop etc.
- Do: app:drawableStartCompat app:drawableTopCompat etc.
As these attributes are part of the appcompat library, be sure to use the app: namespace. Internally these AppCompat* views use AppCompatResources themselves to enable loading vectors.
If you want to understand how appcompat swaps out the TextView etc you declare for an AppCompatTextView which enables this functionality then check out this article: https://helw.net/2018/08/06/appcompat-view-inflation/
In Practice
These requirements effect the way you might create a layout or access resources. Here are some practical considerations.
Views without compat attributes
Unfortunately there are a number of places you may want to specify drawables on views that don’t offer compat attributes (e.g. there’s no indeterminateDrawableCompat attribute for ProgressBar s) i.e. anything not listed above. It’s still possible to use AndroidX vectors, but you’ll need to do this from code:
If you are using Data Binding then this can be accomplished using a custom binding adapter:
Note that we don’t want data binding to load the drawable for us (as it doesn’t use AppCompatResources to load drawables currently) so can’t refer to the drawable directly like @ <@drawable/foo>. Instead we want to pass the drawable id to the binding adapter, so need to import the R class to reference it:
Nested d rawable s
Some drawable types are nestable e.g. StateListDrawable s, InsetDrawable s or LayerDrawable s contain other child drawables. The AndroidX support works by explicitly knowing how to inflate elements (also animated-vector s and animated-selector s, but we’ll focus on static vectors today). When you call AppCompatResources.getDrawable , it peeks at the resource with the given id and if it is a vector (i.e. the root element is ), it manually inflates it for you. Otherwise, it hands it off to the platform to inflate — when doing so, there’s no way for AndroidX to re-insert itself back into the process. That means that if you have an InsetDrawable containing a vector and ask AppCompatResources to load it for you, it will see the tag, shrug, and hand it to the platform to load. It therefore will not get a chance to load the nested so this will either fail (on API AppCompatResources to inflate the vector and then create the InsetDrawable drawable manually.
One exception is a recent addition to AndroidX (from appcompat:1.0.0 ) back-ported AnimatedStateListDrawable s. This is a version of StateListDrawable with animated transitions between states (in the form of AnimatedVectorDrawables ). But there is nothing requiring you to declare transitions. So if you just need a StateListDrawable which can inflate child vectors using AndroidX, then you could use this:
There is a way to enable vectors in nested drawables using AppCompatDelegate#setCompatVectorFromResourcesEnabled but it has a number of drawbacks. Be sure to read the javadoc carefully.
Out of process loading
Sometime you need to provide drawables in places where you don’t control when or how they are loaded. For example: notifications, homescreen widgets or some assets specified in your theme (e.g. setting android:windowBackground which is loaded by the platform when creating a preview window). In these cases you aren’t responsible for loading the drawable so there’s no opportunity to integrate AndroidX support and you cannot use vectors pre-API 21 😞.
You can of course use vectors on API 21+ but be aware that you might not enjoy the features/bugfixes provided by AndroidX. For example while it’s great that AndroidX backports fillType=»evenOdd» , a vector which uses this outside of AndroidX support on an API 21–23 device won’t understand this attribute. For this specific example, I’ll cover how to convert fillType at design time in the next article. Otherwise, you may need to provide alternate resources for different API levels:
Note that we need to include the anydpi resource qualifier here in addition to the api level qualifier. This is due to the way that resource qualifier precedence works; any asset in drawable- dpi would be considered a better match then one in just drawable-v21 .
X Marks the Spot
Hopefully this article has highlighted the benefits of using the AndroidX vector support and some limitations that you need to be aware of. Using the AndroidX support both enables vectors on more platform versions and backports functionality but also sets you up to receive any future updates.
Now that we understand both why and how you should use vectors, the next article dives into how to create them.
Coming soon: Creating vector assets for Android
Coming soon: Profiling Android VectorDrawable s
Источник
How to Add Vector Assets in Android Studio?
Vector Assets in Android Studio helps to add material icons and import Scalable Vector Graphics and Adobe Photoshop Document files into your project as vector drawable resources.
How Vector Asset is different from Image Asset?
Image Asset Studio helps us create different types of icons with different densities and shows us exactly where they’ll be placed in our project. It includes tools for adjusting our icons and adding backdrops, all while displaying the result in a preview pane, so they appear exactly as we intended. Vector Asset Studio helps to add a vector graphic to our project as an XML file that describes the image.
Problem using PNG’s
The PNG format can surely handle high-resolution photos. PNG format is a lossless web format. Hence, file sizes tend to get very large. If we want to work with photos on the web, we should always try to continue with JPEG. And the main issue for printing a .png file is its inherent color profile. The colors of the images may be a little dull since the printer has to interpret a different color language. Each PNG asset which we use is a certain density specific. Therefore, we have to deal with different versions of the same image for different screen sizes. To get rid of such problems we use vector assets.
Bitmap vs Vector
There are the following differences between Bitmap and Vector:
Benefits of Vector Assets
Image scalability is the major advantage of using the vector drawable. The same file can be resized for different screen sizes without loss of image quality which results in smaller APK files and less developer maintenance. We can also use vector images for animation.
How do vector assets render?
The vector assets are first compiled to binary format at compile time and then at runtime. Next, the application is needed to load this up, generates a model object from binary code, and perform some canvas operations to draw the individual paths to the screen.
Vector Formats
There are the following vector file formats:
- .ai: abbreviation for Adobe Illustrator which is commonly used to print media and digital graphics.
- .eps: abbreviation of Encapsulated PostScript which doesn’t support transparency in the way .ai format does.
- .pdf: abbreviation of Portable Document Format which is built for the exchange of documents across platforms.
- .svg: The Scalable Vector Graphics format is based on XML. It’s useful for the web, where it can be indexed, searched, and scripted.
Step by Step Implementation
Step 1: Right-click on drawable > New > Vector Asset
After clicking on Vector Asset a new dialog box is opened that is shown below.
Step 2: Click on Clip Art and Search for the Icons and click ok button
Step 3: Change the color of the icon
Icon color can be changed either by directly adding color code or by adjusting the color using brightness and then click on choose button.
Step 4: Click Next
Step 5: Now Click on Finish Button
Step 6: Icon is created in the drawable folder as shown in the image
Источник