- Understanding Android Adaptive Icons
- Implementing Adaptive Icons
- Understanding Android Adaptive Icons
- Android O introduces a new format for app icons called adaptive icons. To better understand the motivation and…
- Designing Adaptive Icons
- Android O introduces a new app icon format: adaptive icons. Adaptive icons can make devices more coherent by unifying…
- Basics
- Actually minSDK is 26
- VectorDrawable Adaptive Icons
- With Android O finalized as API 26, now’s the time to start thinking about adding an adaptive icon without the bloat of…
- Minimum viable raster
- Take a shortcut
- Play around
- Русские Блоги
- Разница между android: icon и android: roundIcon в приложении
- 8.0 адаптация иконки системного приложения
- Зачем нужно адаптировать иконку приложения?
- 8.0 адаптация иконки системного приложения
- Придется ли мне адаптироваться?
- Создать новый проект
Understanding Android Adaptive Icons
Android O introduces a new format for app icons called adaptive icons. To better understand the motivation and potential of this feature it’s useful to take a look at what it’s replacing.
While Android’s icon guidelines have evolved over time, they have always promoted using unique shapes. I was a huge fan of this! I held that it really helped users to locate the app they wanted to launch. If you want to get nostalgic you can listen to Roman Nurik and I talk about this to 6 whole minutes in an old video we made.
Here’s the ‘traditional’ icon (created by Roman) from Plaid, an app I work on. I believed that the distinct shape helped it to stand out, making it easier to find:
But it’s not all sunshine and rainbows in distinct-shape-icon-land. The flipside of this near-complete creative freedom is lack of consistency. When each individual app is responsible for shape, size and drop-shadow (which is baked into the icon) then the inevitable consequence is that they vary widely. Here’s an example of icons just from Google showing how they at one time varied:
Now admittedly the above image is from 2012 and things have improved a lot in the meantime; especially with the extra guidance in the material guidelines. Nonetheless, I’ve come to believe that the current system places too much responsibility on app developers; giving us too much scope to detract from the overall experience..
When we’re working on an app, we can become laser-focused on it. We rightly spend huge amounts of time pouring over the details that make it unique. We think about it in isolation. But that’s not how users see it; no app is an island and we need to recognize that it exists alongside many other apps on a device. As such it needs to get along. This is true for your entire app but it’s all the more important with elements like app icons which appear side by side. With this framing we can see how instead of our idealized situation, the reality often ends up being more like this:
In response to this problem, a whole cottage industry has sprung up: custom launchers offering icon packs to replace app’s icons or normalize their size. Devices also started shipping with launchers adding backgrounds to app icons to enforce consistency & brand their platform.
Indeed Google’s launcher will start placing icons of apps which target Android-O but do not supply an adaptive icon onto a background (scaling down their non-adaptive icon).
While normalizing icon shapes or sizes is understandable, altering an icon without input from the app developer can’t lead to the best outcome.
Android 7.1 introduced roundIcon as an attempt to bring some consistency here but this was pretty restrictive to OEMs looking to differentiate their devices (i.e. only supporting circular icons) and lacked any kind of validation (developers could supply any shaped icon and pinky-swear that it was round!).
I’d characterize the situation as lacking a well defined contract between the app icons and launchers which will display them. Balancing the complete freedom of icon design against a desire for consistent display currently places responsibilities in the wrong camps. Launchers try to resize icons but don’t understand the content, like which elements are critical and shouldn’t be touched. App icons need to keep up with any guideline changes to ensure they bake in correct sizing/padding or shadow information. I see adaptive icons as making this contract clearer; becoming more explicit about what an app must supply and how a launcher will consume and display it.
For icon makers, it’s easy to see this as losing some freedom. I think this is actually more of a shift rather than a reduction. Adaptive icons introduce new and interesting constraints that open up new creative possibilities. Join me in part 2: designing adaptive icons to explore these.
Источник
Implementing Adaptive Icons
Android O introduces an new application icon format called adaptive icons, intended to make all icons on a device more coherent. This post will look into how to build adaptive icons for your app. It’s unlikely that many apps will be minSdkVersion 26 any time soon, so this post will also examine techniques for adding this additional icon as efficiently as possible.
It’s also worth pointing out that Android Studio 3.0 includes a new wizard to help you to create adaptive icons which we won’t cover here; we’ll stick to the fundamental format and techniques.
If you’re interested in the back story of this format or how to design an adaptive icon the check out these posts:
Understanding Android Adaptive Icons
Android O introduces a new format for app icons called adaptive icons. To better understand the motivation and…
Designing Adaptive Icons
Android O introduces a new app icon format: adaptive icons. Adaptive icons can make devices more coherent by unifying…
Basics
Adaptive icons are a new drawable type, namely AdaptiveIconDrawable . You’ll likely never need to work with the class directly, but to define it in XML and point to it from your manifest. You can do so using this format:
Each drawable must be 108dp*108dp in size; background drawables must be opaque whilst foregrounds can contain transparency.
You also need to build your apk with buildToolsVersion 26.0.0 or higher.
Actually minSDK is 26
Because adaptive icons are only used on API 26+, you can rely on certain features being available to you. Specifically pretty capable VectorDrawable support.
Unfortunately you can’t use custom drawable inflation; as your icon will be loaded by other apps’ processes, you need to stick to platform drawable types.
Utilizing vectors is attractive as it allows us to specify the drawable once in a very compact format. That means it will be crisp at every density without bloating your APK.
In particular, many developers do not seem to have taken advantage of VectorDrawable ‘s support for gradients. On this topic, I’d recommend reading Ian Lake’s recent post on implementing an adaptive icon which covers the basics.
VectorDrawable Adaptive Icons
With Android O finalized as API 26, now’s the time to start thinking about adding an adaptive icon without the bloat of…
Ian shows how to use a simple linear gradient, but VectorDrawable has a few more nifty tricks. Here’s an example of implementing a ‘long-shadow’ using a radial gradient with multiple color stops. I’m also using the inline resource syntax which lets you embed what would be multiple files into a single file (via AAPT tricks, commonly used with AnimatedVectorDrawable s):
Most icons include some kind of drop-shadow element in them (per the material guidelines) which unfortunately VectorDrawable does not support. With adaptive icons, there are two features that make vectors more relevant:
- The launcher is now responsible for masking the overall drawable and providing any drop shadow for the full shape. You no longer have to bake in a shadow for the entire shape.
- The icon is comprised of a background and a foreground image, so if one of those layers does not require any shadows, then it can take advantage of vectors.
Some simple shadows can be approximated using gradients but unfortunately not everything.
Minimum viable raster
If you can’t implement your design with vectors then it’s perfectly fine to do so using PNGs. Your launcher icon is such a crucial asset that it’s definitely worth a few extra bytes to make the right impression.
There is however a neat trick that you can utilize for assets with areas of transparency in them… which is somewhat common in adaptive icon foregrounds. While this kind of asset likely compresses well at build time, at run time each pixel takes up 8 bits of memory no matter what the opacity. To minimize this, if the transparency is around the edges, you can trim these areas from the PNG and use an InsetDrawable to wrap it and fill it out to its 108dp size. Now unfortunately InsetDrawable doesn’t love being resized (i.e. if you set a top inset of 16dp it will always be 16dp no matter how the drawable’s bounds are resized) so in API26 fractional insets were added to mitigate this. This lets you specify insets as a percentage of the overall drawable so they will scale correctly.
For example, say you have a foreground asset which is 54dp*54dp; instead of placing that in a 108dp*108dp asset amidst transparency you can do the following.
Here’s an example using this technique where we remove the top/left portion of the asset which would otherwise contain transparency and instead inset a trimmed version:
Note that you’ll still have to provide the trimmed raster asset at different densities, but at least each will be smaller and in-memory size will be much reduced.
Take a shortcut
Adaptive icons aren’t solely for app icons, they’re also used for app shortcuts. App shortcuts can be pinned to the homescreen so they need to fit in with app icons. The (pre-O) design specs call for shortcut icons to sit on a grey circular background. In Android-O, the background should fill the adaptive icon mask. If you don’t update to adaptive, your shortcut icon will be scaled down and placed on a white background.
To implement this in my app Plaid, I initially added new icons in the v26 configuration, re-drawn for the adaptive grid and keylines. I wasn’t happy with this approach as they were essentially scaled versions of the v25 icons; meaning I now had two icons to maintain. Ultimately I decided to break the v25 icon into a foreground (e.g. the search icon) and background (the grey circle) and combine them with a LayerDrawable :
I could then use the same foreground asset in the adaptive icon. On v25, app shortcut icons are 24dp within a 48dp asset; on v26 they’re 44dp within a 108dp asset:
To use the same 48dp file I needed to inset it so that the icon is the correct size once it’s scaled up (yay vectors!) to the 108dp adaptive icon size. The background is achieved using a ColorDrawable :
AdaptiveIconDrawable will scale the supplied asset to 108dp, so to calculate the inset required to produce a 44dp icon: 48 / 24 * 44 = 88; that is we need to inset the scaled up asset by 10dp each side: 10 / 108 → 9.26%
Play around
If you’re building an adaptive icon, then the Adaptive Icon Playground app might be useful to you. It lets you preview adaptive icons on your device, see how they look with different masks applied and explore some motion effects.
You can grab an APK (for devices already running Android-O) or check it out on github:
Источник
Русские Блоги
Разница между android: icon и android: roundIcon в приложении
8.0 адаптация иконки системного приложения
Зачем нужно адаптировать иконку приложения?
Некоторые друзья могут растеряться. Значок приложения существует с древних времен Android, а функция чрезвычайно проста, достаточно поставить картинку. Что лучше всего подходит для этого? Но на самом деле в текущей среде Android функция значка приложения очень сбивает с толку.
Если мы хотим поговорить об истории значков приложений для мобильных телефонов, мы должны начать с Apple. В 1980-х годах, когда Apple еще разрабатывала компьютеры Lisa и Macintosh, Джобс был ярым сторонником закругленных прямоугольников. В то время инженеры Apple написали замечательный алгоритм, который может рисовать круги и эллипсы на компьютере. Все зрители были шокированы, кроме Джобса, потому что Джобс считал, что хотя круги и эллипсы тоже хороши, если бы они могли нарисовать полосу Еще лучше прямоугольник со скругленными углами. В то время инженер считал, что это невозможно, и что прямоугольники с закругленными углами не нужны вообще, если они соответствуют основным требованиям чертежа. Джобс злобно потащил его по трем улицам, указывал на различные примеры скругленных прямоугольников на улице, и, наконец, на следующий день инженер сделал функцию рисования скругленных прямоугольников.
Поэтому, когда в 2007 году родился iPhone, не все значки приложений былиНеожиданныйЗакругленные прямоугольные значки используются в земле, даже сторонние приложения вынуждены использовать закругленные прямоугольные значки, и это правило сохраняется до сегодняшней iOS 11, как показано на следующем рисунке:
Напротив, когда разрабатывалась система Android, ей не нравилась закрытость и принужденность Apple. Вместо этого она выбрала свободу и открытость и не выдвигала никаких обязательных требований к форме значка приложения. Разработчики могут выбирать:
Как видите, на Android значок приложения может быть квадратом, кругом, прямоугольником с закругленными углами или любой другой неправильной графикой.
Изначально это были разные дизайнерские концепции двух компаний, и трудно сказать, какая из них выше. Но поскольку операционная система Android имеет открытый исходный код, некоторые отечественные производители мобильных телефонов изменили эту функцию при настройке операционной системы. Например, мобильные телефоны Xiaomi решили приблизиться к Apple и заставить значки приложений округляться. Что делать, если значки некоторых приложений не являются прямоугольниками со скругленными углами? Система Xiaomi автоматически добавит к нему эффект закругленных углов, как показано на рисунке ниже:
Такой подход Xiaomi, похоже, учится у Apple, но на самом деле это довольно отвратительно. Поскольку каждый может видеть, что этот автоматически добавленный прямоугольник с закругленными углами очень уродлив, многие компании просто проектируют значки приложений в виде прямоугольников с закругленными углами, и бывает, что Android и iOS используют один и тот же набор значков, чтобы избежать проблем.
Но это огорчает Google. Разве это не изменение, которое заставляет разработчиков создавать значки в виде прямоугольников с закругленными углами? Поэтому на прошлогодней конференции Google I / O Google раскритиковал подход Xiaomi по имени, заявив, что он нарушает философию свободы и открытости Android.
В дополнение к обязательным закругленным углам значка приложения, необходимым для изменения направления, метод обработки Xiaomi имеет еще один недостаток, то есть, если закругленная дуга значка приложения отличается от той, которая требуется системой Xiaomi, произойдет необычно уродливый эффект:
Видеть такие значки приложений действительно неловко. Просто потому, что скругленные углы двух значков приложений предназначены для большего размера, чем закругленные углы, требуемые системой Xiaomi, такие уродливые белые границы добавляются автоматически.
Проблема уже существует, как ее решить? Если честно, это действительно проблема, которая долгое время была головной болью, и Google уже много лет закрывает на это глаза. Наконец, в системе Android 8.0 Google намерен внимательно изучить стандартизацию значков приложений Android, сегодня мы узнаем. Чтобы
8.0 адаптация иконки системного приложения
Эту проблему Google все еще довольно сложно решить. Поскольку Google делает упор на свободу и открытость, для Xiaomi также есть свобода людей заставлять все значки приложений округляться. Нарушает ли это понятие свободы и открытости, если вы запрещаете людям это делать? Конечно, мы здесь, чтобы обсудить это, как сначала обсудить курицу или яйцо, но Google все же нашел идеальное решение.
Начиная с системы Android 8.0, значки приложений разделены на два уровня: слой переднего плана и слой фона. Другими словами, когда мы разрабатываем значок приложения, нам нужно разделить передний план и фон. Передний план используется для отображения логотипа значка приложения, а фон используется для выделения логотипа значка приложения. Следует отметить, что фоновый слой может определять только цвета и текстуры, но не формы.
Так кто же определяет форму значка приложения? Google оставил это право производителям мобильных телефонов. Разве некоторые производители мобильных телефонов не любят изучать округлые значки Apple? Нет проблем, поскольку дизайн значка приложения разделен на два уровня, производителям мобильных телефонов нужно только нанести слой маски поверх этих двух слоев. Эта маска может быть прямоугольником со скругленными углами, кругом, квадратом и т. Д., В зависимости от конкретного производителя мобильного телефона. В зависимости от обстоятельств вы можете мгновенно сделать все значки приложений на телефоне одинаковыми. Принципиальная схема выглядит следующим образом:
Как видите, фоновый слой здесь представляет собой синюю карту сетки, а слой переднего плана — этоРобот AndroidИзображение логотипа, а затем покрыть слоем круглой маски и, наконец, вырезать круглый значок приложения. Чтобы
Придется ли мне адаптироваться?
Некоторые друзья могут подумать, что этот двухслойный дизайн значка приложения слишком громоздкий, может ли он быть неподходящим? Некоторые друзья могут также сказать, что их приложение не адаптировало значок приложения, и оно по-прежнему хорошо работает на телефонах Android 8.0.
Фактически, эта новая функция Google будет постепенно переходить к ней, а не навязывать ее всем разработчикам сразу. Если targetSdkVersion в вашем приложении ниже 26, то нет необходимости адаптировать значок приложения, и система Android 8.0 по-прежнему имеет обратную совместимость. Но если вы укажете targetSdkVersion равным 26 или выше, тогда система Android будет думать, что ваше приложение адаптировано к системе 8.0, что, конечно же, включает в себя адаптацию значка приложения.
Если вы укажете targetSdkVersion равным 26, но не адаптируете значок приложения в системе Android 8.0, какой эффект это будет иметь? Вот несколько отрицательных примеров:
Это снимок экрана телефона Google Pixel с операционной системой Android 8.0. Как видите, значки этих двух приложений очень странные, изначально они были выполнены в виде прямоугольника с закругленными углами, но снаружи расположен белый кружок. Почему так происходит? Это потому, что эти два приложения указали targetSdkVersion на значение выше 26, но они не адаптировали значок приложения в системе 8.0, а маска, установленная телефоном Pixel, является круговой, поэтому она автоматически устанавливается на внешнем слое значка приложения. Белый круг.
Видно, что приложения iQiyi и Ele.me не тестировались на совместимость с Pixel. Однако, учитывая, что они предоставляют услуги только на внутреннем рынке, они такжепростительный。
Конечно, скоро начнется популяризация домашних мобильных телефонов Android 8.0. Я считаю, что никто не хотел бы, чтобы их приложение имело указанные выше эффекты, поэтому давайте начнем конкретно изучать, как адаптировать значки приложений в системе 8.0. . Чтобы
Создать новый проект
Если меня кто-то спросит, сложно ли адаптировать иконку системного приложения 8.0? Отвечу здесь, это совсем не сложно. Я считаю, что каждый, кто прочитал эту статью, может сразу ее изучить, но при этом предполагается, что вам нужен хороший инструмент — Android Studio 3.0 или выше.
Рад сообщить, что в Android Studio 3.0 встроена функция адаптации значков системных приложений 8.0. Если вы установили Android Studio 3.0, поздравляю, у вас все получилось на 90%. Если вы все еще используете старую версию Android Studio, быстро перейдите и обновитесь, а затем прочтите эту статью.
Итак, теперь мы используем Android Studio 3.0 для создания нового проекта, назовем его IconTest.
Источник