React native icons android

React Native — Adding App Icons for Android

Recently, I started dabbling in React Native to prep for a new job. Coming from React, things felt familiar. However, it feels like there is less documentation/articles/tutorials out there compared to anything related to the web (which makes sense — React Native hasn’t even released a v1).

One of the things I’ve been working with is adding an app icon for the Android version of the app I’m building. The goal of this post is to share everything I’ve learned so far so that maybe it will help you avoid any challenges I ran into.

WARNING: As mentioned, I am new to React Native, so please take what I say here with a grain of salt. If you find something that is incorrect, please let me know in the comments.

So let’s get to it! 🕺🏼

What do I need to know?

In order to add app icons (more commonly called «launch icons») to your Android version of your React Native app, there are a few things you need to know:

  • Should my icon be square or round?
  • Where do the icons live within my app?
  • How do I make them?

We’ll tackle these one at a time.

Should my icon be square or round?

The answer is it depends.

Depending on the OEM device, the system will decide whether it will use a «squareish» icon or a round icon. When I ran my app on the Pixel 2 emulator, the square icon was placed «into» a circular icon and it looked ugly 🤮

After looking at the docs, I found this section which explained why that was happening:

You must only use the android:roundIcon attribute if you require a different icon asset for circular masks, if for example the branding of your logo relies on a circular shape.

The logo/icon I was using had a circular shape hence why I had an issue.

In addition to the square and round icons, you may want to create what’s known as an «adaptive icon». According the the Android Developer Docs, «adaptive launcher icons» were introduced in Android 8.0. As of this writing, the latest version is Android 9.0 (also known as Pie).

To summarize, you may need both, depending on the shape of your icon. And you should definitely check out adaptive icons.

Where do the icons live within my app?

Luckily, this answer is pretty straightforward.

Assuming you created your project using the React Native CLI, they will live here:

You’ll have a bunch of different directories that are prefixed with mipmap and suffixed with different sizes like hdpi and mdpi for instance.

These will each contain your icon in different sizes.

How do I make my icons?

I recommend designing your icons in Figma. You should create two layers:

  1. a background layer — the background of the icon
  2. a foreground layer — the icon

I created mine in at 108 x 108 and then exported them as PNGs at 1x.

Then I followed @_s_farias ‘s post called «How to create adaptive icons for Android using Android Studio». This made it very easy to create the icons because Android Studio generated all of them for me and even created most of the necessary subdirectories. 😄

Читайте также:  Meizu m5s обновление до android 7

*One thing to note:

  • I did have to manually create a drawable directory within res . I then copied the files from the mipmap-xxxhdpi to the drawable directory. I don’t know if this is right, but the build succeeded and it worked 🤷🏼‍♂️ (Hoping someone will explain the correct way to do this).

Common Errors

  • Forgetting to update the AndroidManifest.xml file

In the very beginning, I ran into errors because I forgot to update these two lines within this file:

  • resource drawable/ic_launcher_foreground not found

Your build is failing because you didn’t create the drawable directory. See «One thing to note» in previous section.

Anyways — thanks for reading — hope this helps with you React Native Android icons! 🙏🏼

Источник

App Icon in React Native (IOS and Android)

Apr 5, 2020 · 2 min read

App icon is something, uniquely recognises your app from thousands of other out there. Most of the cases, the app icon can be the company/product logo or else some special symbols or any specific part of the name/logo.

Android

From Android 8.0, introduced the concept of adaptive launcher I cons. This icon can self align to depending on the device or launcher application. Concept of adaptive launcher icon is one of many standardisations that Android introduces. To change the icon you just need to replace current icons in mipmap folder named ‘ic_launcher’ and ‘ic_launcher_round’. You can find the same in AndroidManifest.xml. inside application tag. ‘ic’ in ‘ic_launcher’ stands for ‘icon’. We need to add icons in different ‘mipmap’ folders. According to teh phone resolution the device will choose the icon to show.

Android Icon Measurements
Size: 512px x 512px
Format: 32-bit PNG
Color space: sRGB
Max file size: 1024KB
Shape: Full square

In IOS it is pretty much straight forward. Open projectname.xcodeproj/projectname.xcworkspace. On the root directory click on the folder named Images.xcassets.

Drag and drop the icon with the required dimension and it’s done!.

IOS Icon Measurements
Format: PNG
Color space: sRGB/P3
Layers: Flattened with no transparency
Shape: Square with no rounded corners.

Источник

Android adaptive icons and splash screens for React Native projects (2019)

Oct 20, 2019 · 5 min read

The app icon is the first thing your user sees every day when they use your app, and it’s competing for attention with other icons on screen. Therefore it’s very important to get it right.

Why write another Android icon/splash screen article? While there are quite a few tutorials out there covering similar topics, I feel like there is room for an update because some of the answers have changed and a few of the problems we examined here are React Native specific.

Sold? Then let’s begin.

1. Generate Android Adaptive Icons using Android Studio

Before we start, you will need to prepare the artwork for the icon. You can find some ready-made templates in the Resources and tools section near the bottom of this excellent Adaptive Icons Design article.

If you don’t w ant to create the artwork now and just want to try out the steps in this tutorial, you can use this pre-generated one to follow along.

Ready? Let’s open your project in Android Studio and create a new Image Asset in app -> New -> Image Asset

In the Foreground Layer tab, change the image asset Path to your icon artwork. Then switch to the Background Layer tab and add a solid color background, or image if you have one.

Press Next and Finish in the subsequent screens. Now clean and run the Android project again and your new icon should now appear.

2. Android splash screens

Due to differences in how Android activities are handled in React Native’s two major navigation libraries. The splash screen part of this tutorial assumed that you are using Wix’s React-Native-Navigation . I will update this article with steps for React-Navigation in a later date.

Copy splash screen image

If you don’t have a splash screen image handy, you can still follow along with this pre-generated one .

Читайте также:  Как архивировать папку андроид

Navigate to the android -> app -> src -> main -> res folder and paste a copy of your splash screen image into each mipmap-xxxxxxx folder generated from the previous App Icon section. Skip the mipmap-anydpi-v26 folder if you have one or it will cause an error.

Create a splash_screen.xml file

Create a new xml named splash_screen.xml and paste in the content below. Replace logo_splash with the name of your image.

Then create the following folders in android -> app -> src -> main -> res and paste a copy of the newly created splash_screen.xml in each of them.

Create a color.xml file

In the android -> app -> src -> main -> values folder, create a new xml named color.xml and paste in the content below.

Edit the styles.xml file

In the same values folder, you should have a styles.xml

Add a new SplashTheme style item so it look something like below. Note that the splash_screen value here is referencing the name of the splash_screen.xml we created earlier.

Update AndroidManifest.xml

Add the following items to your AndroidManifest.xml
xmlns:tools=”http://schemas.android.com/tools»
android:theme=”@style/SplashTheme”
tools:replace=”android:theme”

Here is an example showing where to place each of them

Solving the white flash problem

If you run the app now, the splash screen will work but if your app has a dark or strong color theme, you might have noticed there is a white flash between React loading and the React-Native-Navigation taking over. To solve this problem, simply edit the MainActivity.java with the content below.

And a solid background color on all navigation screens.

Clean and run the app, you should now see the splash screen when you start the app.

Congratulations! You have reached the end of the article and hopefully an app with proper icons and launch screens. If you like the article and have any feedback or suggestions on how it can better, please leave a comment below. And don’t forget to mash that 👏 button! Thank you for reading and have a nice day.

Источник

Как добавить 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-частью приложения, в место хранения ресурсов:

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

Читайте также:  Android check wifi connection

Заходим в каждую из них и в каждой видим файл 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-версии из корневой папки проекта:

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

Источник

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