- Command-line generation of Android/iOS icons from SVG files.
- Problem
- Solution
- Векторная иконка приложения для Андроид — полное руководство.
- Прежде чем мы начн ём
- Подготовка файлов
- Настройка файлов конфигурации
- Android working with SVG / vector drawables
- 1. What is VectorDrawable?
- 2. Creating Android Project
- 2.1 Creating VectorDrawable from Material Icons.
- 2.2 Creating VectorDrawable from SVG or PSD
- 3. Using VectorDrawable
- 3.1 Using VectorDrawable with ImageView from xml
- 3.2 Using VectorDrawable with ImageView from Java
- 3.3 Using VectorDrawable as Drawable with TextView
- 3.4 Using VectorDrawable to Customise RadioButton
Command-line generation of Android/iOS icons from SVG files.
SVG format has arrived to Android several years ago and can be used quite easily (in most cases). Here is very detailed instruction from official Android Documentation — https://developer.android.com/studio/write/vector-asset-studio.
Problem
But app:srcCompat tag works only for some views, some others still need PNGs. So when you are trying to give them SVG images, the app will not compile (in the best case) or just crash in Runtime.
Of course, you can ping your designer and he will make some PNGs for you. But wait… you bring SVGs into development process by a long discussion with your teammates, designers and even PMs. You probably said, that designer will only need to export one file and it will work everywhere, but now you need to ask him generate some PNGs for you, because don’t have Sketch by yourself — NOT GOOD.
Solution
Of course, there is some command-line solution must exist, because at least Gradle can generate PNGs from SVG for lower APIs.
I’ve not succeeded to find any ready-to-use solution, so I created my own. Script uses librsvg to accomplish the task. Here is the detailed instruction how to use it:
Источник
Векторная иконка приложения для Андроид — полное руководство.
Aug 15 · 4 min read
Однажды копаясь в Андроид документации я с большим удивлением заметил, что в SDK к версии 26 были до б авлены не только адаптивные иконки, но и возможность совсем отказаться от растровых иконок лаунчера на новейших версиях Андроид. Это значит, что вам вовсе не нужно создавать по растровому ассету к каждому разрешению экрана воспользоваться одним/двумя векторными файлами для всех возможных разрешений! Так как растровые иконки достаточно увесистые вы можете таким образом сэкономить много килобайтов в размере приложения. Тут как и везде есть свои моменты и к сожалению я не нашел в интернете полного описания всего процесса. Ну что же, значит пришла моя пора заполнить этот пробел! Ниже вы найдёте видео процесса изготовления единой векторной иконки для приложения, а руководство также доступно на английском и чешском языках.
Прежде чем мы начн ём
Избавится от растровых изображений в целой аппликации — мечта многих оптимизаторов. Особенно если приложения не большое а растровые иконки, при неправильном изготовлении весят почти четверть общего размера приложения. Но тут как и везде есть свои недостатки, давайте поговорим о них, возможно в вашем случае векторная икона — не вариант. Итак:
- Векторный формат в ОС Андроид был введен в версии 21, в качестве иконки приложения в лаунчере векторные изображения можно использовать только в версиях 26 и выше. Это значит, что если Ваше приложение должно поддерживать и более старые версии — Вам все равно придется иметь в наличии растровые иконки. Так что бонус тут не большой.
- Векторный формат который используется в ОС Андроид это не привычные нам SVG/EPS/AI и так далее, это формат XML, а это значит очень ограниченное использование. Этот формат не поддерживает атрибуты стилей, т.е. какие либо эффекты, блендинг, даже простейшие тени, блюр. Вы можете видеть начале видео, что происходит с тенями — они просто пропадают. Если у вас достаточно умелый график в команде, то в принципе это ограничение можно обойти переведя например тени в простые градиенты от полного цвета в абсолютно прозрачный итд. Если же у вас вовсе нет векторного оригинала или там слишком много эффектов — возможно игра не стоит свеч.
На этом минусы заканчиваются. Если ваше приложение должно запускаться лишь на устройствах которые ещё получают закладки безопасности (т.е. в момент написания статьи SDK версии 27+) или же использует какие то новшества современных Андроид систем/датчиков/устройств — векторная иконка отличный выбор. Вы можете сэкономить в несколько раз как на размере так и на файлах для иконки, имея лишь 1-2 файла изображения и пару файлов с их описанием! Звучит круто? Тогда ниже вы найдете рецепт того как это все приготовить.
Подготовка файлов
Я не буду вдаваться в подробности создания файлов иконки, так как они абсолютно идентичны остальным адаптивным иконкам. В интернете буквально тонны всевозможных шаблонов для адаптивных иконок и руководств для них. Можно использовать их все, с той лишь разницей, что в результате мы будем использовать файлы SVG а не PNG. Т.е. это будет один или два файла: первый с задним фоном, который должен иметь область для параллакс эффекта и файл переднего плана. В моем примере я использую вариант где задним фоном служит просто цвет, так что у меня будет один файл с описанием цвета и один файл с векторной графикой.
Итак если вы имеете файл(ы) SVG, то в следующем шаге нам понадобится Android Studio, впрочем если вы занимаетесь разработкой для ОС Андроид, вы и так знаете этот софт. Это бесплатное ПО можно скачать по адресу:
Важно! Векторные ассеты можно создавать лишь в версии 4.2.2 и выше.
Запустите студию, откройте свой проект, после загрузки выберете вкладку Project (первая вкладка слева сверху). В папке с ресурсами с помощью правого клика мыши выведите контекстное меню. В нем выберете первый элемент — New, затем Vector Asset. Откроется Asset Studio, в нем выберете тип: Локальный файл и путь через кнопку с папкой. Проверьте как иконка выглядит и нажмите кнопку Next. Тут вы увидите путь и название к вашему XML файлу с векторной иконкой. Повторите для второго файла если вы используете вектор как в переднем так и на заднем плане. Готово.
Настройка файлов конфигурации
И так изображения готовы, но ваш проект пока не знает пути к ним и как их отобразить. Вам нужно будет добавить/изменить несколько файлов:
- build.gradle — здесь необходимо включить поддержку векторных файлов, просто добавьте эти две строки в конфигурацию и зависимости:
- в папку с ресурсами добавьте папку “ mipmap-anydpi-v26”, т.е. как видно из названия это ассеты для любого DPI в версиях ОС выше 26. В нем будут два файла: ic_launcher_round.xml и ic_launcher.xml в которых необходимо описать что использовать как фон а что как передний план. В моем случае это цвет для фона и векторная графика для переднего плана.
- Ну и на конец то что мы описали в предыдущем пункте нужно добавить в папку drawable а также если вы использовали цвет в качестве фона — описать этот цвет в colors.xml.
Теперь система знает как, где и что, использовать в качестве иконки приложения в лаунчере. Запустите чистую инсталляцию и проверьте результаты своей работы. Как видите, техническая часть достаточно простая (если сравниватъ с PNG иконками).
В результате VCS должна показать вот такие изменения:
Как минимум две новые строки в файле:
./app/build.gradle
Новая папка “ mipmap-anydpi-v26” с двумя файлами:
./app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
./app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
Один XML файл с изображением переднего плана:
./app/src/main/res/drawable/ic_launcher_foreground.xml
И либо описание цвета в качестве фона:
./app/src/main/res/values/colors.xml
либо изображение:
./app/src/main/res/drawable/ic_launcher_background.xml (в данной конфигурации отсутствует).
В ссылке ниже вы найдете все необходимые файлы из примера показанного в видео. Можете использовать их как пример для своего приложения. Спасибо за внимание!
Источник
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)
Источник