- ImageView
- Общая информация
- Метод setImageResource()
- Метод setImageBitmap()
- Метод setImageDrawable()
- Метод setImageURI()
- Другие методы
- Масштабирование через свойство Scale Type
- Атрибут android:adjustViewBounds=»true»
- Загрузка изображения из галереи
- Получить размеры ImageView — будьте осторожны
- Копирование изображений между ImageView
- Примеры
- NativeScript Image Builder
- Upload an Image
- Upload an Icon
- Get Back a Zip
- The Details
- Android Images
- iOS Images
- App Icons
- Meh. Down-sampling
- Other Image Types
- About NativeScript
- Other Resources
- Add images to your Android Project
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.
Источник
NativeScript Image Builder
The NativeScript Image Builder helps you re-size your Android and iOS image assets for using with your NativeScript apps. Upload your maximum resolution image in PNG format, and you’ll get back a .ZIP file with the image assets re-sized.
Upload an Image
To get started, specify your image type, select your image, and press Upload!.
Be sure to upload your highest resolution static image (xxxhpdi or @3x).
Upload an Icon
Select your app icon file, and press Upload!.
For app icons, upload a square image with minimum dimensions of 1024 x 1024.
Get Back a Zip
Android apps should provide 6 image sizes: ldpi (0.75x), mdpi (1.0x), hdpi (1.5x), xhdpi (2.0x), xxhdpi (3.0x), and xxxhdpi (4.0x).
iOS apps should provide 3 image sizes: @1x (iPad 2 and iPad mini), @2x (iPhone 4s, iPhone 5, iPhone 6, iPad [retina]), and @3x (iPhone 6 Plus).
App icons can be even move confusing: Android apps should provide 6 icon sizes, ranging from 36 x 36 pixels to 192 x 192 pixels, plus a Google Play Store app icon of 512 x 512 pixels. iOS apps must include 12 app icons, with varying sizes and pixel densities from 29 x 29 @1x to 60 x 60 @3x (180 pixels), plus several random sizes like the 83.5 x 83.5 @2x to support the iPad Pro.
Upload your image at the highest resolution (xxxhpdi or @3x), and we’ll down-size and rename accordingly.
The Details
Many developers don’t have the time or patience to resize images for their mobile apps, let alone create 8 different versions of an image for a cross-platform app for Android and iOS. Why not out-source it?
Upload a high-dpi version of your static app .PNG images (xxhdpi for Android and @3x for iOS), and we do the heavy lifting. You’ll receive a .ZIP file containing the images down-sampled to the right dimensions for each of the 8 platforms. We’ll also name them correctly for you. Just because we’re nice.
Android Images
When developing Android apps, you should provide 6 different image sizes: ldpi (0.75x), mdpi (1.0x), hdpi (1.5x), xhdpi (2.0x), xxhdpi (3.0x), and xxxhdpi (4.0x). Mdpi images are typically referred to as the «baseline» image, and the other image sizes should be based off of this image’s intent; however, up-sampling from mdpi to xxxhdpi (which is 4x the size) isn’t practical and can lead to pixelated images. So, we ask you to upload your xxxhdpi (4x) image, and we’ll down-sample the image to the other sizes.
In the .ZIP file we’ll send back, we’ll create a directory for each down-sampled image, ready to be copied into your App_Resources\Android folder. Folders are named accordingly: drawable-ldpi, drawable-mdpi, drawable-hdpi, drawable-xhdpi, drawable-xxhdi, drawable-xxxhdpi.
For more details on Android-specific images, check out this article on the Android developer center.
iOS Images
iOS apps require you to to provide 3 sizes of images: @1x (iPad 2 and iPad mini), @2x (iPhone 4s, iPhone 5, iPhone 6, iPad [retina]), and @3x (iPhone 6 Plus). @1x images are typically considered the baseline image size, with @2x and @3x being twice and three times the size, respectively. We won’t up-sample from @1x, so you’ll have to provide the @3x image, and we’ll down-sample for you.
Your .ZIP file will include the three images, ready to be copied into the App_Resources\iOS folder of your NativeScript app. The files will also be named according to their size.
To find out more on iOS images and the requirements of the iOS platform, check out the Apple Developer Center.
App Icons
Creating the «right» app icons (and in the «right» sizes) can be challenging for new developers. There are many great resources online outlining what you need for both Android and iOS platforms.
For Android app icons, we’ll create the 6 different required icon, named icon.png, and place them into their respective drawable folders. We will also create the Google Play Store icon, which is a 512 x 512 pixel icon. This will be placed in the root of the ZIP file Android folder and named playstore-icon.png.
iOS app icons are even more challenging to understand. Apple’s Developer Center outlines exactly what you need, but we still find it hard to understand. We’ll do the heavy lifting and create the various icons, with the proper names, with the standard icon-
Meh. Down-sampling
Yeah. Down-sampling can lead to loss of quality in an image. If this is a concern, this is not the tool for you. You should manually adjust your images, adding and removing detail as you see fit for each of the platforms and image sizes.
Other Image Types
So, there’s also app icons, splash screen images, and a load of other images required by each platform. Support for those is coming.
About NativeScript
NativeScript is an open-source library for building professional cross-platform mobile apps for Android and iOS using JavaScript.
For a more complete reference for using images within your NativeScript app, check out the NativeScript docs.
Other Resources
Check out some of the community support around NativeScript app icons and images.
- iOS image and launch images: Robert Hafner built a Python script to resize iOS images and launch images.
Источник
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.
Источник