- Android Compose Image Tutorial
- Android Jetpack Compose – Image
- Example
- Image Tutorials
- Conclusion
- Загружаемые изображения для Jetpack Compose с использованием Glide, Coil и Fresco
- Загрузка и отрисовка изображений для Jetpack Compose
- Landscapist
- GlideImage
- Различные варианты компоновки на основе состояний запроса
- LocalGlideRequestBuilder
- CoilImage
- LocalCoilImageLoader
- FrescoImage
- Эффект мерцания
- Анимация кругового раскрытия
- CircularRevealedImage
- Палитра
- Заключение
- Loading images for Jetpack Compose using Glide, Coil, and Fresco
- Loading and drawing images for Jetpack Compose
- Landscapist
- GlideImage
- Different Composable based on requesting states
- LocalGlideRequestBuilder
- CoilImage
- LocalCoilImageLoader
- FrescoImage
- Shimmer effect
- Circular reveal animation
- CircularRevealedImage
- Palette
- Conclusion
Android Compose Image Tutorial
Android Jetpack Compose – Image
Image composable function is used to display image in Android application.
The most basic code of an Image composable to display an image from drawable resources is as shown in the following.
We can also modify the shape or its look using optional parameters.
Example
Add an image to the Resources using Resource Manager. You may drag and drop the image in Drawable section in Resource Manager as shown in the following picture.
Go through the steps, and the image would be added to the resources.
We shall display this image in our Application using Image composable.
MainActivity.kt
Screenshot
Image Tutorials
The following is a list of tutorials, that cover styling and how-to concepts with Text composable.
Conclusion
In this Android Jetpack Compose Tutorial, we learned what Image composable is, and how to style the Image composable, with the help of individual tutorials for each concept.
Источник
Загружаемые изображения для Jetpack Compose с использованием Glide, Coil и Fresco
Новый современный набор инструментов пользовательского интерфейса Jetpack Compose был анонсирован компанией Google более года назад, и, наконец, в июле была выпущена стабильная версия 1.0. Также многие компании, такие как Twitter, lyft, Square, уже адаптировали Jetpack Compose на своих производственных уровнях, потому что он очень интуитивный, мощный и упрощает всю структуру пользовательского интерфейса, если правильно его использовать. Эта новая парадигма структуры пользовательского интерфейса поменяет в дальнейшем очень многое, также нам придется приложить еще немало усилий для миграции предыдущих вещей, связанных с пользовательским интерфейсом, таких как загрузка изображений из Url.
Загрузка и отрисовка изображений для Jetpack Compose
Когда Google анонсировал Jetpack Compose 1.0.0-alpha01, я задался вопросом, как мы должны перенести все предыдущие системы, связанные с пользовательским интерфейсом, в проекты Jetpack Compose? Простое получение изображений из Url (сети) и рисование на компонуемых Image потребовало бы совершенно иного подхода, чем раньше. В то время была выпущена библиотека accompanist Криса Бейнса, и она меня очень вдохновила. Эта библиотека поддерживала Coil (позже появилась поддержка Glide), но я хотел использовать и предоставить как можно больше вариантов для выбора библиотек загрузки изображений. Потому что миграция целых систем загрузки изображений (например, с Glide на Coil) может доставить разработчикам немало хлопот. Поэтому Landscapist был создан для поддержки многих вариантов, таких как Glide, Coil и Fresco для Jetpack Compose.
Landscapist
Landscapist — это библиотека загрузки изображений для Jetpack Compose. Есть три варианта: Glide, Coil и Fresco. Таким образом, мы можем выбирать по своему вкусу. Эта библиотека также поддерживает анимацию загрузки, например, эффект мерцания и круговое раскрытие. Если вы хотите узнать больше о применении этой библиотеки, то можете обратиться к демонстрационным проектам, использующим Landscapist для рисования изображений.
GlideImage
Мы можем загружать и рисовать изображения из Url с помощью компонуемой функции GlideImage , как показано ниже. Это довольно просто.
Мы также можем предоставить основные атрибуты, такие же, как у компонуемого Image , например contentScale и modifier .
Если мы хотим показать плейсхолдер (загрузка) и изображение ошибки в зависимости от состояния выборки, то можем использовать атрибуты placeHolder и error , как показано ниже.
Различные варианты компоновки на основе состояний запроса
Иногда нам необходимо реализовать разные пользовательские интерфейсы в зависимости от состояния запроса. В принципе, мы можем использовать различные варианты компоновки в зависимости от состояния загрузки/успеха/ошибки. Приведенный ниже пример показывает индикатор, когда состояние запроса загружается, и отображает компонуемый элемент Text , когда запрос не выполняется. При успешном запросе будет показано загруженное изображение.
Если мы хотим настроить свою композицию успеха, мы также можем настроить результат пользовательского интерфейса успеха, как показано ниже. Лямбда success передает состояние запроса, и мы можем получить ImageBitmap из его инстанса.
LocalGlideRequestBuilder
CompositionLocal — одна из наиболее часто используемых концепций в Jetpack Compose, и в официальном справочнике Android она описывается следующим образом.
Compose передает данные через дерево композиции в явном виде посредством параметров к компонуемым функциям. Часто это самый простой и лучший способ передачи данных по дереву. CompositionLocals можно использовать как неявный способ передачи данных через композицию.
Landscapist также поддерживает CompositionLocal для предоставления RequestBuilder (основа запроса в Glide) в компонуемом потоке данных.
CoilImage
Coil — это почти то же самое, что и Glide , только вместо GlideImage используется CoilImage .
Также мы можем предоставить множество пользовательских атрибутов, таких как Glide.
LocalCoilImageLoader
Также поддерживает CompositionLocal для обеспечения подобия ImageLoader в компонуемой иерархии.
FrescoImage
Fresco немного отличается от описанных выше, перед его использованием следует инициализировать пайплайн изображений. Если нам нужно получать изображения из сети, рекомендуем использовать OkHttpImagePipelineConfigFactory .
Используя ImagePipelineConfig , мы можем настраивать стратегии кэширования, работу в сети и пул потоков. Вот другие ссылки, которые связаны с конфигурацией пайплайна.
Также и другие вещи почти не отличаются от вышеупомянутых библиотек.
Эффект мерцания
Landscapist поддерживает эффект мерцания при загрузке изображений из сети, и мы можем реализовать его с помощью ShimmerParams . В примере ниже используется CoilImage , но ShimmerParams также можно применить для GlideImage и FrescoImage .
Можно настроить все детали ShimmerParam , используя baseColor , highlightColor , durationMillis , dropOff и tilt .
Анимация кругового раскрытия
Landscapist поддерживает анимацию кругового раскрытия при показе изображений. Это можно реализовать очень просто, задав для атрибута circularRevealedEnabled значение true .
CircularRevealedImage
Мы можем использовать составное изображение CircularRevealedImage независимо от библиотек загрузки (Glide, Coil, Fresco) и реализовать анимацию кругового раскрытия, используя наше рисованное изображение ресурса.
Мы должны установить параметр circularRevealedEnabled в true , если хотим применить анимацию кругового раскрытия, также можно изменить продолжительность анимации с помощью атрибута circularRevealedDuration .
Палитра
Landscapist поддерживает API палитры для извлечения цветовых профилей из изображений. В основном, необходимо использовать BitmapPalette для извлечения основных цветов из изображений, как показано ниже. И можно ссылаться на типы цветов здесь.
Мы можем настроить больше опций, используя interceptor и paletteLoadListener .
Заключение
В этом посте мы рассмотрели, как загружать и рисовать изображения для Jetpack Compose с помощью Landscapist. К большому удовольствию, эта библиотека используется многими мировыми компаниями, включая Twitter. Ее путь начался с Jetpack Compose 1.0.0-alpha, и на данный момент она уже была выпущена более 30 раз, пока не достигла Jetpack Compose 1.0 stable. К счастью, я получил массу вдохновения и помощи от accompanist (спасибо, Крис Бейнс! спасибо за все Google Compose, Android Team!); и это долгое путешествие, кажется, только начинается.
Материал подготовлен в рамках курса «Android Developer. Professional». Всех желающих приглашаем на двухдневный онлайн-интенсив «Android Lint». На нем мы:
— изучим Android Lint API;
— научимся писать кастомные Lint детекторы и тесты на них;
— разберемся, как правильно подсвечивать контекст и реализовывать LintFix’ы;
— напишем несколько проверок на частые ошибки использования популярных библиотек.
>> РЕГИСТРАЦИЯ
Источник
Loading images for Jetpack Compose using Glide, Coil, and Fresco
A new modern UI toolkit Jetpack Compose has been announced by Google over a year ago, and finally, it has been released 1.0 stable in July. Also many kinds of companies like Twitter, lyft, Square already have been adapted the Jetpack Compose in their production levels because it is very intuitive, powerful, and simplifies the entire UI structure if we use it well. This new paradigm of the UI structure will change a lot of things in our future, also we have to do more efforts to migrate the previous UI-related things like loading images from Url.
Loading and drawing images for Jetpack Compose
When Google announced Jetpack Compose 1.0.0-alpha01, I was wondered that how should we migrate all of the previous UI-related systems to Jetpack Compose projects? Simply fetching images from an Url (network) and drawing on the Image composable would require a completely different process from before. At that time, accompanist by Chris Banes has been released and I was got many inspired by the library. The library supported Coil (Glide was supported later), but I wanted to use and provide as many as possible options to choose image-loading libraries. Because migrating the entire image loading systems (e.g., from Glide to Coil) could give a hundred of pain to developers. So Landscapist was created to support many options like Glide, Coil, and Fresco for Jetpack Compose.
Landscapist
Landscapist is an image loading library for Jetpack Compose. There are three options; Glide, Coil, and Fresco. So we can choose by our preference. This library also supports loading animations like shimmer effect and circular reveal. If you want to look up more usages of this library, you can reference demo projects that using Landscapist for drawing images.
GlideImage
We can load and draw images from an Url using a GlideImage composable function like the below. That’s quite simple.
We also can give basic attributes same as the Image composable like contentScale and modifier .
If we want to show a placeholder (loading) and an error image based on the fetching state, we can use the placeHolder and error attributes like the below.
Different Composable based on requesting states
Sometimes we need to implement different UI based on requesting states. Basically, we can implement different composables based on the loading/success/error states. The below example shows an indicator when the requesting state is loading, and it will show a Text composable when it goes fail. If the request succeeds, it will show a loaded image.
If we want to custom your success composable, we can also custom the success UI result like the below. The success lambda passes a state of the requesting, and we can get an ImageBitmap from the state instance.
LocalGlideRequestBuilder
CompositionLocal is one of the most used concepts in the Jetpack Compose, and the official Android reference describes it like the below.
Compose passes data through the composition tree explicitly through means of parameters to composable functions. This is often times the simplest and best way to have data flow through the tree. CompositionLocal s can be used as an implicit way to have data flow through a composition.
Landscapist also supports the CompositionLocal for providing like RequestBuilder (the backbone of the request in Glide) in the composable data flow.
CoilImage
Coil is almost the same as the Glide, it uses CoilImage instead of the GlideImage .
Also we can give many kinds of custom attributes like Glide.
LocalCoilImageLoader
Also supports the CompositionLocal for providing like ImageLoader in the composable hierarchy.
FrescoImage
Fresco is a little different from the above, we should initialize an image pipeline before to use. If we need to fetch images from the network, recommend using OkHttpImagePipelineConfigFactory .
By using an ImagePipelineConfig , we can customize caching, networking, and thread pool strategies. Here are more references related to the pipeline config.
Also other things are almost the same as the above libraries.
Shimmer effect
Landscapist supports shimmer effect when loading images from network, and we can implement it using a ShimmerParams . The below example uses CoilImage but we can also apply the ShimmerParams for GlideImage and FrescoImage .
We can customize the details of the ShimmerParam using baseColor , highlightColor , durationMillis , dropOff , and tilt .
Circular reveal animation
Landscapist supports circular reveal animation when showing images. This can be implemented very simply by giving the circularRevealedEnabled attribute as true .
CircularRevealedImage
We can use CircularRevealedImage composable regardless of image loading libraries (Glide, Coil, Fresco) and we can implement circular reveal animation using our drawable resource image.
We should set the circularRevealedEnabled as true if we want to apply circular reveal animation, also we can change the duration of the animation using circularRevealedDuration attribute.
Palette
Landscapist supports palette APIs for extracting color profiles from images. Basically, we should use BitmapPalette to extract major colors from images like the below. And we can reference color types here.
We can customize more options using like interceptor and paletteLoadListener .
Conclusion
In this post, we looked around how to load and draw images for Jetpack Compose using Landscapist. Very thankfully, this library has been used by many global companies including Twitter. This journey started from the Jetpack Compose 1.0.0-alpha and now it has been released more than 30 times until reaches the Jetpack Compose 1.0 stable. Luckily, I got a lot of inspired and helped from accompanist (Thank you, Chris Banes! and thanks for all the Google Compose, Android Team!), and this long journey seems to just get started. 🛫
Источник