- Векторная иконка приложения для Андроид — полное руководство.
- Прежде чем мы начн ём
- Подготовка файлов
- Настройка файлов конфигурации
- Android app icon vector
- Android app icon vector
- VectorDrawable Adaptive Icons
- The basics of adaptive icons
- Round icons
- Building a VectorDrawable Background
- Building a VectorDrawable Foreground
- All the benefits, none of the APK bloat
Векторная иконка приложения для Андроид — полное руководство.
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 app icon vector
You have no collections yet
All collections displayed here
What can I do with my collections?
Click on any icon you’d like to add to the collection.
Organize your collections by projects, add, remove, edit, and rename icons.
Use the «Paint collection» feature and change the color of the whole collection or do it icon by icon.
Download your collections in the code format compatible with all browsers, and use icons on your website.
Save a backup copy of your collections or share them with others- with just one click!
You have reached your collections limit. Upgrade to get unlimited collections
Register and create new collections
Are you sure you want to delete this collection?
We are sorry you canceled your Premium subscription
You can still enjoy Flaticon Collections with the following limits:
- You can choose only 3 collections to keep
- You can only add up to 100 icons per collection
- You cannot add Premium icons to your collection
The advantages of your collections changed
- You can choose only 3 collections to keep
- You can only add up to 100 icons per collection
- You cannot add Premium icons to your collection
Keep making the most of your icons and collections
Get 20% OFF our
Annual Premium Plan
Источник
Android app icon vector
You have no collections yet
All collections displayed here
What can I do with my collections?
Click on any icon you’d like to add to the collection.
Organize your collections by projects, add, remove, edit, and rename icons.
Use the «Paint collection» feature and change the color of the whole collection or do it icon by icon.
Download your collections in the code format compatible with all browsers, and use icons on your website.
Save a backup copy of your collections or share them with others- with just one click!
You have reached your collections limit. Upgrade to get unlimited collections
Register and create new collections
Are you sure you want to delete this collection?
We are sorry you canceled your Premium subscription
You can still enjoy Flaticon Collections with the following limits:
- You can choose only 3 collections to keep
- You can only add up to 100 icons per collection
- You cannot add Premium icons to your collection
The advantages of your collections changed
- You can choose only 3 collections to keep
- You can only add up to 100 icons per collection
- You cannot add Premium icons to your collection
Keep making the most of your icons and collections
Get 20% OFF our
Annual Premium Plan
Источник
VectorDrawable Adaptive Icons
So the Android O APIs are final — API 26 is here! That means you can start compiling with API 26 right now (and you should really always compile with the latest SDK) as well as work towards targeting API 26.
One of the first things you should consider working on is providing an adaptive icon — an icon made of a separate background and foreground layer. This new format provides a consistent shape across all icons on a device and will also allow launchers to add visual effects by animating the background and foreground separately. This is really how you make a good first impression for users with Android O devices.
With the system handling the outer edge shape and its shadow, adaptive icons give you a chance to re-evaluate how you build your app icon. If you’re able to build your app icon as an SVG/vector image, consider avoiding bloating your app with more PNGs for the background and foreground and take advantage of VectorDrawables for your adaptive icon.
Note: there are valid cases where PNGs are the correct choice for your app. Talk to your designer before trying to force everything into vector drawables.
I’ll walk you through what it took to convert Muzei’s current icon into an adaptive icon.
Note: you do not need to target API 26 to provide an adaptive icon — only compile against it. Users will benefit from your work even as you work through other behavior changes.
The basics of adaptive icons
By placing it in the mipmap-anydpi-v26 folder, the resource system will use it in preference over any files in the other dpi folders (exactly what you want, since this file is replacing all of them) and that it should only be used in API 26+ devices.
You’ll notice that the drawables are in the drawable directory. This is because I’m using vector drawables. If you are using PNGs, this should most definitely be in mipmap . Another option is use a color resource for your background:
Round icons
For those of you with an android:roundIcon , you must keep that attribute to continue to support API 25 devices. Devices with round masks will use your custom roundIcon if available, but it is strongly suggested to use a single adaptive icon for those devices as well (this ensures you get the standard shadow, support for visual effects, etc).
I find this easiest by creating an alias resource. You’d keep your ic_launcher_round images in the res/mipmap directories for API 25 devices, but add a file in your values-anydpi-v26 folder:
Building a VectorDrawable Background
The background is a great place to start. Being a full bleed 108 x 108 dp image, there’s not much special about this one:
Just keep in mind that due to the masking of the image, users will usually only see the middle 72 x 72 dp.
Building a VectorDrawable Foreground
The foreground image, on the other hand, offers a unique challenge.
First, you have to handle creating the foreground shape itself. It is still on the same 108 x 108 dp artboard, but the ‘safe zone’ of what you know will be shown is only a middle circle of radius 33 dp — don’t put anything critical outside of that part!
Where I initially got stuck was when it comes to the traditional 45º material cast shadow that the foreground also needs to include. Normally, this would be where you’d have to break out the PNGs to get that perfect gradient. But gradient support was added to VectorDrawables back to API 24!
Getting gradients working, however, required a bit of research. The VectorDrawable docs point out the ability to use a GradientColor , but where to find a good example? On StackOverflow of course.
Now, Roman Nurik, the maker of the original Muzei icon, had made a fantastic SVG version of the launcher icon including the shadow as a
element in the SVG. I won’t pretend that I know how he came up with the correct values — talk to your local designers or read the material design guidelines for product icons a couple hundred times.
But what it became was a res/color/ic_launcher_shadow.xml file that looks like this:
You’ll note all of the attributes from the GradientColor documentation available to customize this to be just right.
Note: As of Android Studio 3.0 Canary 3, Android Studio flags gradient as an error (‘Element gradient must be declared’). It still works.
Now, we can refer to our gradient color the same way you’d refer to a color: with @color/ic_launcher_shadow in the VectorDrawable . In Muzei’s case, this means that the foreground background consists of two paths: the shadow and then the shape below it:
Note: this is also how you’d add a finish layer to your icon — a separate gradient above your shape as explained in the material design guidelines.
All the benefits, none of the APK bloat
By taking advantage of API 24’s addition of gradients to VectorDrawables, we can build well designed VectorDrawable adaptive icons that have the correct material shadows on foreground elements without resorting to adding even more PNGs into the app.
If you want to see it in action, join Muzei’s open beta, then download Muzei on an Android O Dev Preview 3 device and check out the commit that added the adaptive icon. (Although unless you have the superhuman ability to visualize VectorDrawables like Nick Butcher, you might find the full commit doesn’t add much over the code we already covered.)
For further information, you might want to check out Nick Butcher’s excellent series of articles on adaptive icons.
Источник