Setting app icon android

How to Create Android App Icons using Image Asset Studio

Creating an application interface that the user will like and will be unlikely to forget can be intimidating. But creating an attractive launcher icon for your app, that the user will first come across while looking at your app, anyway needs more brainstorming. For Android, you need to create these graphics that have to be compatible and supporting to all devices running Android, sizes varying from a smartphone to TV. The introduction of Android Image Asset Studio in Android Studio has made it easy. In this article, you will see how you can easily create your application icon in one go.

Image Asset Studio is a tool introduced in Android Studio 3. It can be used to generate app icons for all the screen densities in one go, using custom images, material design icons as well as text strings. Application icon in Android includes the following,

  • Launcher Icon: represents your app and the first thing that user sees
  • ActionBar Icon & Tab Icon: representing actions in the ActionBar and Tabs of the app
  • Notification Icon: represents your app notification when a user is outside your app

Here is a list of icon/image sizes that you need to create for different screen densities, for each image that you use in your application. No matter if you are a good designer, creating each of these is tedious!

Image Asset Studio helps to create all these icons for all screen densities and stores them in respective density folders. It provides a preview of all the icons that will be created, in different shapes, with options to edit them. Let’s see how to create each one of them.

Run Image Asset Studio

  1. In the Project Window, select the project hierarchy.
  2. Right-click on the res folder and choose New -> Image Asset.

3. Create the icon for your app i.e.

  • Launcher icon which may be Adaptive and Legacy Launcher Icon (if your app supports Android 8.0 or above) or just the Legacy Launcher Icon(for Android version less than or equal to 7.1)
  • ActionBar Icons and Tab Icons
  • notification icon as per your requirement.

4. You can select the following Asset Type. The icon appears on the right side, in the preview panel.

Custom Image

You can use custom images of PNG (recommended), JPG or GIF (avert) format and adjust it to create icons. Set the path of your custom image if you select this.

Clip Art

You can select the icons from the list of Google Material Design Icons provided in the dialog. Click on the clip art icon to get the dialog with icon set.

Text String

You can use the fonts installed on your computer to generate the icons out of the text strings. It will create these text-based icons in PNG format in respective drawable-density folders. Set the string and select the font to use it.

If you are comfortable learning from video, you can refer to this for Launcher Icons and App Bar Icons:

Creating Launcher Icon

Launcher Icons represent our app in the device home screen, on the app list screen, in the Google Play Store and everywhere else. Android 8.0 (Oreo) and above supports Adaptive Icons and can be displayed in different shapes across various platforms. Image Asset Studio provides the option to create these adaptive icons as well as the legacy icons for Android 8.0 below. It also creates web icons(512 x 512 px) that represents our app on the Google Play Store.

The Launcher Icons are stored in the res/mipmap-density folder.

Adaptive and legacy launcher icon

If your app doesn’t support android version 8.0 or above, create legacy icon only for your app.

After opening Image Asset Studio, follow the steps below to create the legacy icons for your android app.

  1. For Icon Type field, select Launcher Icons (Adaptive & Legacy).
  2. For Foreground Layer tab, select the Asset type to be an image, clip art or text.
  3. Then for the Background Layer tab, select a Color or set the Image path for the Asset type to set the background.
  4. Then the Legacy tab, check the default settings. You can choose whether you want to generate the legacy icon, round icon and the icon for the web(Google Play Store Icon).
  5. Optionally
  • Name: Change the name of the foreground and background layer. If the resource with the specified name exists, it will be indicated by an error message. The name can contain lowercase characters, digits and underscore only.
  • Trim: Chose yes to adjust the margin between the foreground icon graphic and the background, else select no to keep the source asset as it is.
  • Color: Set the color for the clip art or the text asset. Click the field, select the color, click chose and preview your icon.
  • Resize: Use the slider to resize your icon. It is disabled for background layer where Color is the asset type.
Читайте также:  Что делать если повреждены архивы андроида

7. Chose the resource directory for your image asset.

  • main/res: For all source set including debug and release
  • debug/res: For debugging only
  • release/res: For only one version of build, overrides main source set
  • custom source set: To define a new source set File -> Project structure -> app -> Build Types. Refer to Configure Build Variants for details
    Output Directories shows the list of folders in which the icons will be created in the Project view in Project Window.

Check the mipmap folders for the Launcher Icons.

Legacy launcher icon only

If your app supports android version 8.0 or above, create adaptive and legacy launcher icon for your app.

After opening Image Asset Studio, follow the steps below to create adaptive and legacy icons for your android app.

  1. For Icon Type field, select Launcher Icons (Legacy Only).
  2. Select the Asset type to be an image, clip art or text.
  3. Optionally
  • Name: Change the name of the icon if you don’t want to use the default name. If the resource with the specified name exists, an error message will indicate it. The name can contain lowercase characters, digits and underscore only.
  • Trim: Chose yes to adjust the margin between the foreground icon graphic and the background, else select no to keep the source asset as it is.
  • Padding: Adjust the source set padding for all four sides. You will have the review on the right side.
  • Foreground: Set the color for the clip art or the text asset. Click the field, select the color, click chose and preview your icon.
  • Background: Set the color for the background. Click the field, select the color, click chose and preview your icon.
  • Scaling: Select crop or S hrink to fit to fit the icon size
  • Shape: Select the shape to set a backdrop for the icon. For transparent, select none.
  • Effect: Select dogear if you want the dogear effect for your icon, else select none.

5. Chose the resource directory for your image asset.

  • main/res: For all source set including debug and release
  • debug/res: For debugging only
  • release/res: For only one version of the build, overrides main source set
  • custom source set: To define a new source set File -> Project structure -> app -> Build Types. Refer to Configure Build Variants for details

Check the mipmap folders for the Launcher Icons.

Creating ActionBar Icons and Tab Icons

ActionBar icons are the ones present on the ActionBar that represents individual action. Whereas, the tab icons are used in the apps having multiple tabs. Using material icons for this category is recommended.

The ActionBar and Tab Icons are stored in the res/drawable-density folder.

You can also use Vector Asset Studio to have XML vectors for these categories of icons. It will reduce the size of your APK considerably.

After opening Image Asset Studio, follow the steps below to create action bar and tab icons for your android app.

  1. For Icon Type field, select Action Bar and Tab Icons.
  2. Select the Asset type to be an image, clip art or text.
  3. Optionally
  • Name: Change the name of the icon if you don’t want to use the default name. If the resource with the specified name exists, an error message will indicate it. The name can contain lowercase characters, digits and underscore only.
  • Trim: Chose yes to adjust the margin between the foreground icon graphic and the background, else select no to keep the source asset as it is.
  • Padding: Adjust the source set padding for all four sides. You will have the review on the right side.
  • Theme: Select holo_light or holo_dark as per your app theme. Select custom to set a custom color for the icon.
Читайте также:  Как сменить заставку блокировки экрана андроид

5. Chose the resource directory for your image asset.

  • main/res: For all source set including debug and release
  • debug/res: For debugging only
  • release/res: For only one version of build, overrides main source set
  • custom source set: To define a new source set File -> Project structure -> app -> Build Types. Refer to Configure Build Variants for details

Check the drawable folders for the Icons created.

Creating Notification icons

To learn from the video:

The user sees the notification when he is outside your app. Notification icons come up with these notifications.

The Notification Icons are stored in the res/drawable-density folder. There are a few other folders created too.

  • for Android 2.2 (API 8) or lower — icons stored in res/drawable-density
  • for Android 2.3 to 2.3.7 (API 9 & 10) — icons stored in res/drawable-density-v9. Gray version of the icon is created
  • Android 3 (API 11) or higher — icons stored in res/drawable-density-v11. A white version of the icon is created.

After opening Image Asset Studio, follow the steps below to create notification icons for your android app.

  1. For Icon Type field, select Notification Icons.
  2. Select the Asset type to be an image, clip art or text.
  3. Optionally
  • Name: Change the name of the icon if you don’t want to use the default name. If the resource with the specified name exists, an error message will indicate it. The name can contain lowercase characters, digits and underscore only.
  • Trim: Chose yes to adjust the margin between the foreground icon graphic and the background, else select no to keep the source asset as it is.
  • Padding: Adjust the source set padding for all four side. You will have the review on the right side.

5. Chose the resource directory for your image asset.

  • main/res: For all source set including debug and release
  • debug/res: For debugging only
  • release/res: For only one version of build, overrides main source set
  • custom source set: To define a new source set File -> Project structure -> app -> Build Types. Refer to Configure Build Variants for details

Check the drawable folders for the Icons created.

How to Delete an App Icon from a project

To delete the app icon,

  1. Select Android View in Project Window
  2. Expand the mipmap and drawable folder for the launcher and other icons respectively.
  3. Select the sub-folder that matched the name of your icon. It contains the icons of all densities that you created.
  4. Right-click on the sub-folder and hit delete.
    Dialog for Safe Delete appears.
  5. If you want, select options to find the places where the icon is used and hit OK.
    If you chose to search for usage and the icon has any use in the project, you can view it and then confirm delete. You should delete or replace this reference to successfully compile the project. Android Studio then deletes the file from the project and the drive.
  6. Chose Build -> Clean Project.

Источник

Как добавить AppIcon и LaunchScreen в приложение на React Native

Не занимаясь никогда ранее нативной разработкой под мобильные платформы, и в этот раз решил пойти «легким путем» — освоить React Native. Наибольшей трудностью стало добавление иконки приложения(AppIcon) и экрана загрузки (Launch Screen). О чем и хочу рассказать в данной статье тем, кто осваивает React Native.

На момент написания статьи актуальная версия React Native 41.0, XCode 8.2 (эти данные указаны по той причине, что в более поздних версиях может что-то измениться и данный мануал не будет применим).

Создаем React Native приложение

Добавление AppIcon

На iOS

Идем в папку с iOS-частью приложения

и открываем там файл XCode-проекта habr.xcodeproj.

Далее, щелкаем по следующим кнопкам:

В поле 4 добавляем иконки путем перетаскивания их в пустые ячейки. Под ячейками указан размер иконки(в pt).

Получается примерно так:

Важно: картинка иконки должна быть квадратная и, в идеале, их должно быть несколько версий разного размера(под каждую ячейку — свой размер). Если не охота возиться с созданием иконок разного размера — добавьте одну, размером 120x120px, в ячейку для iPhone 7-10:

Читайте также:  Для андроид эш против зловещих мертвецов

Если добавить иконки не правильного размера, то получите ошибку «Images.xcassets: The app icon set named “AppIcon” did not have any applicable content.»

Полезно знать: иконки для ios удобнее всего создавать в программе Sketch(доступна только под OS X), поскольку в ней есть шаблоны нужных размеров, которые затем можно экспортировать в png-формат (File → Export. ):

Запускаем сборку ios-версии из корневой папки проекта:

(hit: для «сворачивания» приложения в эмуляторе нужно дважды нажать Cmd+Shift+H)

На Android

Из папки проекта идем в папку с Android-частью приложения, в место хранения ресурсов:

и видим здесь папки:

Заходим в каждую из них и в каждой видим файл ic_launcher.png. Заменяем каждый файл на свой, с таким же именем и такого же размера (в px).

Запускаем сборку Android-версии из корневой папки проекта:

С иконками закончили, переходим к экрану загрузки.

Добавление LaunchScreen

На iOS

Существует по крайней мере 2 способа добавить LaunchScreen на iOS. Опишу тот, который сработал у меня.

Первым делом, идем снова в XCode, по тому же маршруту, который показан на самом первом изображении в этой статье, но вместо папки Images.xcassets, выбираем файл LaunchScreen.xib.

При этом XCode спросит, для какой версии какого устройства отобразить содержимое данного файла. Выбираем любой iPhone.

Далее, щелкаем по кнопкам под номером 3 и 4 на данном скриншоте:

Затем перетаскиваем элемент 5 (Image View) на рабочее поле 6. Имеющиеся в рабочем поле 6 элементы (текстовые надписи) можно удалить.

Следующим шагом добавляем в наш проект нужное нам файл с изображением(для начинающих маководов — контекстное меню вызывается прикосновением к тачпаду двумя пальцами одновременно).

Далее, щелкаем по элементу UIImageView в рабочей зоне и настраиваем его свойства:

В меню под номером 1 (на скриншоте) выбираем добавленную в предыдущем шаге картинку(если выпадающий список пуст, то щелкните в левой панели(там где выбирали файл LaunchScreen.xib по любому другому файлу, а затем снова вернитесь к файлу LaunchScreen.xib — файл появится в выпадающем списке. Это мелкий баг XCode).

В меню под номером 2 выберите «Aspect Fit», чтобы картинка масштабировалась пропорционально, независимо от размера экрана устройства, на котором будет запущено приложение.

Чтобы картинка располагалась строго по центру, щелкните самой картинке(на рабочей области) и нажмите на кнопку 1, как показано на следующем скриншоте:

В каждом из четырех полей «Add new constrains» установите значение 0.

Запускаем сборку ios-версии из корневой папки проекта:

На Android

Из папки проекта идем в папку с Android-частью приложения, в место хранения ресурсов:

Добавляем здесь папку drawable. Создаем в ней файл splash_screen.xml такого содержания

Этот файл описывает новый «ресурс» приложения, и путь к внешним файлам ресурса(в нашем случае — к файлу с изображением для стартового экрана).

эта часть кода указывает расположение ресурса на экране. А эта:

путь к файлу ресурса, относительно папки res.

Создает фоновую подложку к экрану загрузки, а строка

указывает цвет фона. Значение цвета фона берется из файла colors.xml, который пока не существует и который вам нужно создать и расположить по адресу:

Содержимое файла может быть таким:

Здесь каждая строчка вроде

содержит цветовую константу. Задать цветовое значение фона напрямую(в файле splash_screen.xml) мне не удалось, поэтому добавил такой файл, как советовалось в одной из инструкций в Сети.

Далее, в папку drawable добавляем файл ic_launcher.png, представляющий собой изображение на стартовом экране.

Затем идем в папку

и редактируем файл styles.xml так, чтобы он выглядел следующим образом

Этим действием мы добавляем новую «тему оформления» для «активности»(activity).

«Активность»(Activity) в Android-приложениях представляет собой «экран» или «страницу». По умолчанию в React Native есть лишь одна «активность», мы же добавляем ещё одну.

Для этого переходим в папку с java-кодом:

(путь после /java/ в вашем проекте будет другим) и делаем следующее:

  1. переименовываем MainActivity.java в MainActivity2.java
  2. редактируем файл MainActivity2.java — меняем название класса в 6 строке с «MainActivity» на «MainActivity2»:

Создаем файл MainActivity.java, в который пишем такой код:

Смысл перечисленных выше 3-х шагов прост: мы меняем стартовый загрузочный экран(«активность») на наш экран(«активность) SplashScreen.

(В этом абзаце вы могли заметить, что LaunchScreen переименовался в SplashScreen. В Android-разработке(и не только) принято называть загрузочный экран SplashScreen’ом.)

Теперь осталось зарегистрировать нашу «активность» в файле-манифесте Android-приложения, чтобы она была доступна для вызова в коде.

Открываем файл AndroidManifest.xml, который находится по адресу

(относительно корневой директории проекта)

И приводим его к такому виду:

В итоге, в файле AndroidManifest.xml мы имеем 2 активности, причем в одной из них указано, что именно она — та, с которой начнется запуск Android-приложения. Это делается добавлением таких параметров:

в тело «активности».

С приготовлениями закончено. Запускаем билд android-версии из корневой папки проекта:

Полный код проекта можно найти здесь.

Источник

Оцените статью