- ImageView
- Общая информация
- Метод setImageResource()
- Метод setImageBitmap()
- Метод setImageDrawable()
- Метод setImageURI()
- Другие методы
- Масштабирование через свойство Scale Type
- Атрибут android:adjustViewBounds=»true»
- Загрузка изображения из галереи
- Получить размеры ImageView — будьте осторожны
- Копирование изображений между ImageView
- Примеры
- Load Image From a Remote URL with Kotlin and Glide
- XML Layout File
- Load Image with Glide Example in Kotlin
- Load GIF from a Remote URL with Glide
- Как загрузить ImageView по URL-адресу в Android? [закрытый]
- 23 ответов
- Android ImageView in Kotlin with Example
- Android ImageView in Kotlin Example
- Handy ImageView Tricks
- Remove extra space above and below imageView
- Tutorialwing
- Output
- Getting Started
- Creating New Project
- Setup ViewBinding
- Using ImageView in Kotlin
- Different Attributes of ImageView in XML
- Set Id of ImageView
- Set Width of ImageView
- Set Height of ImageView
- Set Padding of ImageView
- Set Margin of ImageView
- Set Background of ImageView
- Set Visibility of ImageView
- Different Attributes of Android ImageView Widget
ImageView
Общая информация
Компонент ImageView предназначен для отображения изображений. Находится в разделе Widgets.
Для загрузки изображения в XML-файле используется атрибут android:src, в последнее время чаще используется атрибут app:srcCompat.
ImageView является базовым элементом-контейнером для использования графики. Можно загружать изображения из разных источников, например, из ресурсов программы, контент-провайдеров. В классе ImageView существует несколько методов для загрузки изображений:
- setImageResource(int resId) — загружает изображение по идентификатору ресурса
- setImageBitmap(Bitmap bitmap) — загружает растровое изображение
- setImageDrawable(Drawable drawable) — загружает готовое изображение
- setImageURI(Uri uri) — загружает изображение по его URI
Метод setImageResource()
Сначала нужно получить ссылку на ImageView, а затем используется идентификатор изображения из ресурсов:
Метод setImageBitmap()
Используется класс BitmapFactory для чтения ресурса изображения в объект Bitmap, а затем в ImageView указывается полученный Bitmap. Могут быть и другие варианты.
Метод setImageDrawable()
Если у вас есть готовое изображение, например, на SD-карте, то его можно использовать в качестве объекта Drawable.
Drawable можно получить и из ресурсов, хотя такой код выглядит избыточным, если можно сразу вызвать setImageResource().
Метод setImageURI()
Берётся URI файла изображения и используется в качестве источника изображения. Этот способ годится для работы с локальными изображениями.
Загружаем Drawable через URI.
Другие методы
Также вам часто придется использовать методы, связанные с размерами и масштабированием: setMaxHeight(), setMaxWidth(), getMinimunHeight(), getMinimunWidth(), getScaleType(), setScaleType().
Масштабирование через свойство Scale Type
Для масштабирования картинки в ImageView есть свойство Scale Type и соответствующий ему атрибут android:scaleType и перечисление ImageView.ScaleType.
- CENTER
- CENTER_CROP
- CENTER_INSIDE
- FIT_CENTER
- FIT_START
- FIT_END
- FIT_XY
- MATRIX
Чтобы увидеть разницу между разными режимами, желательно использовать большую картинку, превосходящую по ширине экрана устройства. Допустим, у нас есть простенькая разметка:
Для наглядности я задал красный цвет для фона ImageView.
Режим android:scaleType=»center» выводит картинку в центре без масштабирования. Если у вас будет картинка большего размера, то края могут быть обрезаны.
Режим android:scaleType=»centerCrop» также размещает картинку в центре, но учитывает ширину или высоту контейнера. Режим попытается сделать так, чтобы ширина (или высота) картинки совпала с шириной (или высотой) контейнера, а остальное обрезается.
Режим android:scaleType=»centerInside» масштабирует картинку, сохраняя пропорции. Можно увидеть задний фон контейнера, если его размеры отличаются от размера картинки.
Режим android:scaleType=»fitCenter» (по умолчанию) похож на предыдущий, но может не сохранять пропорции.
Если выбрать режим android:scaleType=»fitStart», то картинка прижимается к левому верхнему углу и таким образом заполняет верхнюю половину контейнера.
Значение android:scaleType=»fitEnd» сместит картинку в нижнюю часть контейнера.
Режим android:scaleType=»fitXY» растягивает/сжимает картинку, чтобы подогнать её к контейнеру. Может получиться вытянутая картинка, поэтому будьте осторожны.
Последний атрибут android:scaleType=»matrix» вывел картинку без изменений в левом верхнем углу с обрезанными краями.
Атрибут android:adjustViewBounds=»true»
При использовании атрибута scaleType=»fitCenter» из предыдущего примера Android вычисляет размеры самой картинки, игнорируя размеры ImageView. В этом случае ваша разметка может «поехать». Атрибут adjustViewBounds заставляет картинку подчиниться размеру компонента-контейнера. В некоторых случаях это может не сработать, например, если у ImageView установлен атрибут layout_width=»0dip». В таком случае поместите ImageView в RelativeLayout или FrameLayout и используйте значение 0dip для этих контейнеров.
Загрузка изображения из галереи
Предположим, у вас есть на экране компонент ImageView, и вы хотите загрузить в него какое-нибудь изображение из галереи по нажатию кнопки:
Намерение ACTION_PICK вызывает отображение галереи всех изображений, хранящихся на телефоне, позволяя выбрать одно изображение. При этом возвращается адрес URI, определяющий местоположение выбранного изображения. Для его получения используется метод getData(). Далее для преобразования URI-адреса в соответствующий экземпляр класса Bitmap используется специальный метод Media.getBitmap(). И у нас появляется возможность установить изображение в ImageView при помощи setImageBitmap().
На самом деле можно поступить ещё проще и использовать метод setImageURI.
Сравните с предыдущим примером — чувствуете разницу? Тем не менее, приходится часто наблюдать подобный избыточный код во многих проектах. Это связано с тем, что метод порой кэширует адрес и не происходит изменений. Рекомендуется использовать инструкцию setImageURI(null) для сброса кэша и повторный вызов метода с нужным Uri.
В последних версиях системных эмуляторов два примера не работают. Проверяйте на реальных устройствах.
Получить размеры ImageView — будьте осторожны
У элемента ImageView есть два метода getWidth() и getHeight(), позволяющие получить его ширину и высоту. Но если вы попробуете вызвать указанные методы сразу в методе onCreate(), то они возвратят нулевые значения. Можно добавить кнопку и вызвать данные методы через нажатие, тогда будут получены правильные результаты. Либо использовать другой метод активности, который наступает позже.
Копирование изображений между ImageView
Если вам надо скопировать изображение из одного ImageView в другой, то можно получить объект Drawable через метод getDrawable() и присвоить ему второму компоненту.
Примеры
В моих статьях можно найти примеры использования ImageView.
Источник
Load Image From a Remote URL with Kotlin and Glide
In this Kotlin programming tutorial I am going to share with you how to load image from a remote URL in Kotlin using Glide.
Glide is probably the easiest and the most efficient way to load image to an ImageView. You can use Glide to load a local image and well as an image hosted on a remote server.
Here are some benefits of using glide:
- It does automatic caching,
- It optimizes image size,
- Ever got memory overload when loading an image and then your app crashes? If you use Glide you will never get this kind of problem.
In this example we will load image from a remote URL to an ImageView using Glide.
First we will need to add these dependencies to our project in the app level build.gradle file.
XML Layout File
Below is my XML layout file which contains a Linear Layout to which I am going to add an ImageView.
Load Image with Glide Example in Kotlin
The below Kotlin code example shows how to create an ImageView and then use Glide to load an image from a remote URL.
Load GIF from a Remote URL with Glide
Now, if we want to load a Gif file from a remote URL, the code example will be slightly different. Notice the use of .asGif()
If you run this code example, you should get the following view on your mobile device:
Load Image with Kotlin and Glide
I hope that this Kotlin programming tutorial was helpful for you. Checkout my other Kotlin code examples in the Android->Kotlin category.
Also, if you would like to learn more about Kotlin and how to build mobile apps for Android platform with Kotlin check our the list of books and video courses below.
Источник
Как загрузить ImageView по URL-адресу в Android? [закрытый]
Как вы используете изображение, на которое ссылается URL в ImageView ?
23 ответов
убедитесь, что у вас есть следующие разрешения установить в свой AndroidManifest.xml для доступа в интернет.
сначала вам нужно загрузить изображение
затем используйте Imageview.setImageBitmap для установки растрового изображения в ImageView
1. Пикассо позволяет без проблем загружать изображения в вашем приложении-часто в одной строке кода!
Использовать Gradle:
только одна строка кода!
2. скольжения библиотека загрузки и кэширования изображений для Android, ориентированная на плавную прокрутку
использовать Gradle в:
// для простого просмотра:
3. фреска — это мощная система для отображения изображений в Android приложения.Fresco заботится о загрузке и отображении изображений, поэтому у вас нет к.
Я написал класс, чтобы справиться с этим, поскольку это, похоже, повторяющаяся потребность в моих различных проектах:
UrlImageViewHelper заполнит ImageView с найденным изображением по URL.
образец сделает Изображение Google Поиск и загрузка/показать результаты асинхронно.
UrlImageViewHelper будет автоматически загрузите, сохраните и кэшируйте все URL-адреса изображения в BitmapDrawables. Дубликаты url не будут загружаться в память дважды. Битовая память управляется используя слабую справочную хэш-таблицу, так что как только изображение больше не будет используется вами, это будет мусор собранные автоматически.
в любом случае люди просят мой комментарий опубликовать его в качестве ответа. я отправляю.
Источник
Android ImageView in Kotlin with Example
In this tutorial, we will create an Android ImageView in Kotlin with the help of an example. Android ImageView extends the View class. As the name suggests ImageView is used to display an image on the screen.
The image can be bitmap or a drawable resource file. We can show images programmatically and using the xml code as well.
ImageView in Android is one of the fundamental UI widget element. It is hard to find any application that is not using images. Today we are going to learn how to add an image using ImageView in Kotlin programming.
Android ImageView in Kotlin Example
First of all, let’s set an image view using ImageView XML code. In the given XML we have an image, text and a button.
activity_main.xml
Some of the XML properties that are used in activity_main.xml
XML Attribute | Description |
---|---|
android:id | Id is the unique identifier |
android:scaleType | It is used to scale the image and set the position |
android:src | It is used to set a drawable source file |
MainActivity.kt
In the MainActivity.kt we are implemented button click and on the button click, we are changing the image programmatically.
Run the app and see the output.
Before Change Image Button Clicked
After Change Image Button Clicked
Handy ImageView Tricks
Remove extra space above and below imageView
You can set the image view bounds using android:adjustViewBounds=»true» property. You can also scale the image to fit x and y-direction using android:scaleType=»fitXY»
Источник
Tutorialwing
In this article, we will learn about android ImageView using Kotlin. We will go through various example that demonstrates how to use different attributes of ImageView. For example,
In this article, we will get answer to questions like –
- What is ImageView?
- Why should we consider ImageView while designing ui for any app?
- What are possibilities using ImageView while designing ui? etc.
Let’s have a quick demo of things we want to cover in this tutorial –
Output
Tutorialwing Kotlin ImageView Output
Tutorialwing Kotlin ImageView Output
Getting Started
We can define android ImageView widget as below –
ImageView is subclass of view that displays image. It is also used to handle image tinting and scaling.
Now, how do we use ImageView in android application ?
Creating New Project
At first, we will create an application.
So, follow steps below to create any android project in Kotlin –
Step | Description |
---|---|
1. | Open Android Studio (Ignore if already done). |
2. | Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next. |
3. | In next screen, select project name as ImageView. Then, fill other required details. |
4. | Then, clicking on Finish button creates new project. |
Some very important concepts (Recommended to learn before you move ahead)
Before we move ahead, we need to setup for viewBinding to access Android ImageView Using Kotlin file without using findViewById() method.
Setup ViewBinding
Add viewBinding true in app/build.gradle file.
Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.
Now, we can access view in Kotlin file without using findViewById() method.
Using ImageView in Kotlin
Follow steps below to use ImageView in newly created project –
- Open res/values/strings.xml file. Then, add below code into it.
- Open res/layout/activity_main.xml file. Then, add below code in it –
- We can also access it in Kotlin File, MainActivity.kt, as below –
Here, we have accessed imageView using kotlin file (i.e. MainActivity.kt file) in the application. Then, we have set an image resource in it. After that, we have set a click listener on button that will change the button in the imageView whenever it is clicked. Similarly, you can perform any operation in imageView.
Now, run the application. We will get output as below –
Tutorialwing Kotlin ImageView Output
Tutorialwing Kotlin ImageView Output
Different Attributes of ImageView in XML
Now, we will see how to use different attributes of Android ImageView using Kotlin to customise it –
Set Id of ImageView
Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of ImageView using android:id attribute like below –
Here, we have set id of ImageView as imageView_ID using android:id=”” attribute. So, if we need to reference this ImageView, we need to use this id – imageView_ID.
Learn to Set ID of ImageView Dynamically
Set Width of ImageView
We use android:layout_width=”” attribute to set width of ImageView.
We can do it as below –
Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of ImageView Dynamically
Set Height of ImageView
We use android:layout_height=”” attribute to set height of ImageView.
We can do it as below –
Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of ImageView Dynamically
Set Padding of ImageView
We use android:padding=”” attribute to set padding of ImageView.
We can do it as below –
Here, we have set padding of 10dp in ImageView using android:padding=”” attribute.
Learn to Set Padding of ImageView Dynamically
Set Margin of ImageView
We use android:layout_margin=”” attribute to set margin of ImageView.
We can do it as below –
Here, we have set margin of 10dp in ImageView using android:layout_margin=”” attribute.
Learn to Set Margin of ImageView Dynamically
Set Background of ImageView
We use android:background=”” attribute to set background of ImageView.
We can do it as below –
Here, we have set background of color #ff0000 in ImageView using android:background=”” attribute.
Learn to Set Background of ImageView Dynamically
Set Visibility of ImageView
We use android:visibility=”” attribute to set visibility of ImageView.
We can do it as below –
Here, we have set visibility of ImageView using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of ImageView Dynamically
Till now, we have see how to use android ImageView using Kotlin. We have also gone through different attributes of ImageView to perform certain task. Let’s have a look at list of such attributes and it’s related task.
Different Attributes of Android ImageView Widget
Below are the various attributes that are used to customise android ImageView Widget. However, you can check the complete list of attributes of ImageView in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –
Some of the popular attributes of imageView are –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:adjustViewBounds | Use this attribute to auto adjust imageView’s boundaries to maintain the aspect ratio of it’s drawable |
2 | android:baseline | It is used to set the offset of the baseline within this view. |
3 | android:baselineAlignBottom | It is used to set the baseline aligned with it’s bottom edge. |
4 | android:cropToPadding | It is used to crop the image to fit within it’s padding |
5 | android:maxHeight | It is used maximum height of the view. |
6 | android:maxWidth | It is used maximum width of the view. |
7 | android:scaleType | It is used to define the way image will be resized or moved to match the size of the imageView |
8 | android:src | It is used to set a drawable of the imageView |
9 | android:tint | It is used to tint the color of the image. |
10 | android:tintMode | It is used to set blending mode used to apply the image tint |
Some of the popular attributes of ImageButton inherited from View are –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:alpha | It is used to set alpha of the view |
2 | android:autofillHints | It is used to set the data to be shown to auto fill in the view |
3 | android:background | It is used to set background of the view |
4 | android:backgroundTint | It is used to set tint to apply to the background |
5 | android:backgroundTintMode | It is used to set blending mode used to apply the background tint |
6 | android:clickable | It is used to set whether this view is clickable or not |
7 | android:elevation | It is used to set elevation to the view |
8 | android:fitsSystemWindows | It is used to adjust view layout based on system windows |
9 | android:focusable | Controls whether this view can take focus |
10 | android:id | It is used to set unique id to the view |
11 | android:onClick | It is used to define what to do when this view is clicked |
12 | android:padding | It is used to set padding to the view |
13 | android:tag | It is used to set tag to the view |
14 | android:tooltipText | It is used to set tooltip text to be shown when hovered on the view |
15 | android:visibility | It is used to set visibility of the view |
We have seen different attributes of ImageView and how to use it. If you wish to visit post to learn more about it
Thus, we have seen what is ImageView, how can we use android ImageView using Kotlin ? etc. We also went through different attributes of android ImageView.
Источник