- Moving images on the screen in Android
- ImageView
- Общая информация
- Метод setImageResource()
- Метод setImageBitmap()
- Метод setImageDrawable()
- Метод setImageURI()
- Другие методы
- Масштабирование через свойство Scale Type
- Атрибут android:adjustViewBounds=»true»
- Загрузка изображения из галереи
- Получить размеры ImageView — будьте осторожны
- Копирование изображений между ImageView
- Примеры
- Add images to your Android Project
Moving images on the screen in Android
Moving various objects is often used in mobile games and various multimedia applications. In this article, we will look at how to add images to the screen and move them freely.
To do this, we need to perform the following steps:
- Create layout with the FrameLayout component.
- Create an ImageView programmatically for the added image and set it to OnTouchListener
- Define user actions in the onTouch() method
- Change LayoutParams values according to the current ImageView location
First, create a new project with empty activity.
In the activity_main.xml layout, delete the old layout and replace it with the new one. In this case, FrameLayout will be used as a container for added images.
Define the created layout elements in the MainActivity code.
To select and crop added images, we use the uCrop library, which can be found on GitHub. Implement it by adding the following lines to the project’s build.gradle file:
Then, in the build.gradle file of the app module, you need to implement the library itself:
After that, you need to register library activity in the AndroidManifest.xml of the application.
Now you need to get images to add to the application. With the help of intent, we call the file manager, with which we find the appropriate images on the device. To do this, set up button click handler as follows.
To get the Uri of the selected file, you need to override the onActivityResult() method in the activity code, adding the following code to it:
The getFileName() method is used to get the file name from Uri, you can see it in the source code of the project later.
When we have the Uri of the selected file, we can use the uCrop library to crop the image as we need. This can be done using the following lines in the startCrop() method.
After calling start(), library activity will open in which you can work with the image. As soon as the work is finished, the intent with the Uri of the cropped image will return to our activity. In this case, it will be easier for us to access the file itself, since its path and name are known. You can get it all in the same onActivityResult() as follows.
Here we immediately create a new ImageView, to which we set the size and load the Bitmap obtained from the file into it.
Now images are simply added to the screen and you can’t interact with them in any way. To handle touches for images, we add the OnTouchListener variable to the activity code, in which the onTouch() method will be overrided. This method allows you to catch various touches and gestures, but we only need the following user actions:
- User touched image;
- The user moves a finger across the screen;
- The user removed his finger from the screen;
Thus, the processing code will look like this:
Here we determine the current coordinates of the image when the user touches it, then calculate the change in coordinates and update them in the image when the user removes a finger from the image. There is also a condition due to which the image should not go beyond the screen.
Now all that remains is to set this touch handler for the created ImageView in createImageView().
That’s all. Now, by launching the application, we can freely move images around the screen.
Thus, with a few lines of code, you can create a simple application for interacting with images on the screen.
You can view the source code of the application by clicking on the link to GitHub.
Источник
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.
Источник
Add images to your Android Project
We’re now going to add a picture to Android Studio. This picture will be used in an Image View.
First, download this picture: (Right click and select Save Image As.)
Save it to your own computer and remember where you saved it to.
We need to import this picture into the res > drawable folder. Open up your Project Explorer again by clicking its tab:
Now expand the res item and locate the drawable folder:
Right click the drawable folder, and select Show in Explorer from the menu:
This will open a window showing a list of folders. The image below is from Windows 10:
All of these folders are from your res directory. (The mipmap ones are used mainly for icons. You can create them in different sizes. We’ll do this much later in the course.)
What you need to do is to copy and paste your image from where you saved it on your computer into the drawable folder (we’re assuming you know how to copy and paste files from one folder to another):
Now go back to Android Studio and you should see it there:
We can now use this image in our app.
Go back to your blueprint. Locate the Image View control in the Palette, which is under Images in earlier versions of Android Studio:
In later versions of Android Studio, you can find the Image View control under the Common category of the Palette (and under Widgets):
Drag an Image View to just below your Text View. As soon as you do, you should the following dialogue box appear:
Expand the Project item of Drawable and select the bridge image and click OK. Your blueprint will then look like this:
As you can see, the Image View has ended up in the top left. We don’t want it there.
With the Image View selected, click anywhere inside of it with your left mouse button. Keep the left mouse button held down and drag it below the Text View:
(You won’t be able to see the image itself in Blueprint View.)
Now we’ll add a Constraint. We want to connect the top middle circle of the Image View to the bottom middle circle of the Text View. Hold your mouse over the top middle circle of the Image View. It will turn green. Now hold your left mouse button down. Keep it held down and drag to the bottom middle circle of the Text View:
You should see a blue arrow connecting the two:
Now add a constraint from the left of the Image View to the left edge of the screen, just like you did for the Text View. Likewise, connect the right edge of the Image View to the right edge of the screen. Your blueprint will then look like this:
It can be a little bit fiddly, so don’t forget you can undo with CTRL + Z.
If you have a look at the properties area again, you may be wondering what all those lines are for:
The straight lines indicate which sides of your view are constrained, and to where. They also tell you the size of the margins, 8 in the image above. Hold your mouse over one of the lines and you’ll see a dropdown list. You can change your margins from here:
The other lines to be aware of are the ones inside the square, pointy arrows in the image above. There are three different settings here:
Wrap Contents
Fixed
Match constraints
Click the arrows to see what they do. Watch what happens to the Image View when you click a set of arrows. In the image below, we’ve set the arrows to Fixed:
The arrows have turned into straight lines. Notice that layout_width value has changed to 200dp. It has changed to 200 because that was the width of the image we used. Notice that the Image View hasn’t changed its size. But move the horizontal slider from 50 to something else. Watch what happens to your Image View in the blueprint.
Click the straight lines inside the square to see the third of the settings, Match Constraints:
Notice that image has now stretched to the margins of the screen. Notice, too, that the layout_width has been reset to zero. Click again, though, to go back to Wrap Contents.
In the next lesson, you’ll learn about a different type of layout — LinearLayout.
Источник