Android drawable from resource file

Drawable Resources

See also

A drawable resource is a general concept for a graphic that can be drawn to the screen and which you can retrieve with APIs such as getDrawable(int) or apply to another XML resource with attributes such as android:drawable and android:icon . There are several different types of drawables:

Bitmap File A bitmap graphic file ( .png , .jpg , or .gif ). Creates a BitmapDrawable . Nine-Patch File A PNG file with stretchable regions to allow image resizing based on content ( .9.png ). Creates a NinePatchDrawable . Layer List A Drawable that manages an array of other Drawables. These are drawn in array order, so the element with the largest index is be drawn on top. Creates a LayerDrawable . State List An XML file that references different bitmap graphics for different states (for example, to use a different image when a button is pressed). Creates a StateListDrawable . Level List An XML file that defines a drawable that manages a number of alternate Drawables, each assigned a maximum numerical value. Creates a LevelListDrawable . Transition Drawable An XML file that defines a drawable that can cross-fade between two drawable resources. Creates a TransitionDrawable . Inset Drawable An XML file that defines a drawable that insets another drawable by a specified distance. This is useful when a View needs a background drawble that is smaller than the View’s actual bounds. Clip Drawable An XML file that defines a drawable that clips another Drawable based on this Drawable’s current level value. Creates a ClipDrawable . Scale Drawable An XML file that defines a drawable that changes the size of another Drawable based on its current level value. Creates a ScaleDrawable Shape Drawable An XML file that defines a geometric shape, including colors and gradients. Creates a ShapeDrawable .

Also see the Animation Resource document for how to create an AnimationDrawable .

Note: A color resource can also be used as a drawable in XML. For example, when creating a state list drawable, you can reference a color resource for the android:drawable attribute ( android:drawable=»@color/green» ).

Bitmap

A bitmap image. Android supports bitmap files in three formats: .png (preferred), .jpg (acceptable), .gif (discouraged).

You can reference a bitmap file directly, using the filename as the resource ID, or create an alias resource ID in XML.

Note: Bitmap files may be automatically optimized with lossless image compression by the aapt tool during the build process. For example, a true-color PNG that does not require more than 256 colors may be converted to an 8-bit PNG with a color palette. This will result in an image of equal quality but which requires less memory. So be aware that the image binaries placed in this directory can change during the build. If you plan on reading an image as a bit stream in order to convert it to a bitmap, put your images in the res/raw/ folder instead, where they will not be optimized.

Bitmap File

A bitmap file is a .png , .jpg , or .gif file. Android creates a Drawable resource for any of these files when you save them in the res/drawable/ directory.

file location: res/drawable/filename.png ( .png , .jpg , or .gif )
The filename is used as the resource ID. compiled resource datatype: Resource pointer to a BitmapDrawable . resource reference: In Java: R.drawable.filename
In XML: @[package:]drawable/filename example: With an image saved at res/drawable/myimage.png , this layout XML applies the image to a View:

The following application code retrieves the image as a Drawable :

XML Bitmap

An XML bitmap is a resource defined in XML that points to a bitmap file. The effect is an alias for a raw bitmap file. The XML can specify additional properties for the bitmap such as dithering and tiling.

Note: You can use a element as a child of an element. For example, when creating a state list or layer list, you can exclude the android:drawable attribute from an element and nest a inside it that defines the drawable item.

file location: res/drawable/filename.xml
The filename is used as the resource ID. compiled resource datatype: Resource pointer to a BitmapDrawable . resource reference: In Java: R.drawable.filename
In XML: @[package:]drawable/filename syntax: elements: Defines the bitmap source and its properties.

xmlns:android String. Defines the XML namespace, which must be «http://schemas.android.com/apk/res/android» . This is required only if the is the root element—it is not needed when the is nested inside an . android:src Drawable resource. Required. Reference to a drawable resource. android:antialias Boolean. Enables or disables antialiasing. android:dither Boolean. Enables or disables dithering of the bitmap if the bitmap does not have the same pixel configuration as the screen (for instance: a ARGB 8888 bitmap with an RGB 565 screen). android:filter Boolean. Enables or disables bitmap filtering. Filtering is used when the bitmap is shrunk or stretched to smooth its apperance. android:gravity Keyword. Defines the gravity for the bitmap. The gravity indicates where to position the drawable in its container if the bitmap is smaller than the container.

Читайте также:  The talking angela для андроид

Must be one or more (separated by ‘|’) of the following constant values:

Value Description
top Put the object at the top of its container, not changing its size.
bottom Put the object at the bottom of its container, not changing its size.
left Put the object at the left edge of its container, not changing its size.
right Put the object at the right edge of its container, not changing its size.
center_vertical Place object in the vertical center of its container, not changing its size.
fill_vertical Grow the vertical size of the object if needed so it completely fills its container.
center_horizontal Place object in the horizontal center of its container, not changing its size.
fill_horizontal Grow the horizontal size of the object if needed so it completely fills its container.
center Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.
fill Grow the horizontal and vertical size of the object if needed so it completely fills its container. This is the default.
clip_vertical Additional option that can be set to have the top and/or bottom edges of the child clipped to its container’s bounds. The clip is based on the vertical gravity: a top gravity clips the bottom edge, a bottom gravity clips the top edge, and neither clips both edges.
clip_horizontal Additional option that can be set to have the left and/or right edges of the child clipped to its container’s bounds. The clip is based on the horizontal gravity: a left gravity clips the right edge, a right gravity clips the left edge, and neither clips both edges.

android:mipMap Boolean. Enables or disables the mipmap hint. See setHasMipMap() for more information. Default value is false. android:tileMode Keyword. Defines the tile mode. When the tile mode is enabled, the bitmap is repeated. Gravity is ignored when the tile mode is enabled.

Must be one of the following constant values:

Value Description
disabled Do not tile the bitmap. This is the default value.
clamp Replicates the edge color if the shader draws outside of its original bounds
repeat Repeats the shader’s image horizontally and vertically.
mirror Repeats the shader’s image horizontally and vertically, alternating mirror images so that adjacent images always seam.

example: see also:

  • BitmapDrawable
  • Creating alias resources

Nine-Patch

A NinePatch is a PNG image in which you can define stretchable regions that Android scales when content within the View exceeds the normal image bounds. You typically assign this type of image as the background of a View that has at least one dimension set to «wrap_content» , and when the View grows to accomodate the content, the Nine-Patch image is also scaled to match the size of the View. An example use of a Nine-Patch image is the background used by Android’s standard Button widget, which must stretch to accommodate the text (or image) inside the button.

Same as with a normal bitmap, you can reference a Nine-Patch file directly or from a resource defined by XML.

For a complete discussion about how to create a Nine-Patch file with stretchable regions, see the 2D Graphics document.

Nine-Patch File

XML Nine-Patch

An XML Nine-Patch is a resource defined in XML that points to a Nine-Patch file. The XML can specify dithering for the image.

file location: res/drawable/filename.xml
The filename is used as the resource ID. compiled resource datatype: Resource pointer to a NinePatchDrawable . resource reference: In Java: R.drawable.filename
In XML: @[package:]drawable/filename syntax: elements: Defines the Nine-Patch source and its properties.

xmlns:android String. Required. Defines the XML namespace, which must be «http://schemas.android.com/apk/res/android» . android:src Drawable resource. Required. Reference to a Nine-Patch file. android:dither Boolean. Enables or disables dithering of the bitmap if the bitmap does not have the same pixel configuration as the screen (for instance: a ARGB 8888 bitmap with an RGB 565 screen). example:

Читайте также:  Добавить свое устройство андроид

Layer List

A LayerDrawable is a drawable object that manages an array of other drawables. Each drawable in the list is drawn in the order of the list—the last drawable in the list is drawn on top.

Each drawable is represented by an element inside a single element.

Источник

Работа с изображениями

Ресурсы изображений

Одним из наиболее распространенных источников ресурсов являются файлы изображений. Android поддерживает следующие форматы файлов: .png (предпочтителен), .jpg (приемлем), .gif (нежелателен). Для графических файлов в проекте уже по умолчанию создана папка res/drawable . По умолчанию она уже содержит ряд файлов — пару файлов иконок:

При добавлении графических файлов в эту папку для каждого из них Android создает ресурс Drawable . После этого мы можем обратиться к ресурсу следующим образом в коде Java:

Например, добавим в проект в папку res/drawable какой-нибудь файл изображения. Для этого скопируем на жестком диске какой-нибудь файл с расширением png или jpg и вставим его в папку res/drawable (для копирования в проект используется простой Copy-Paste)

Далее нам будет предложено выбрать папку — drawable или drawable-24 . Для добавления обычных файлов изображений выберем drawable :

Здесь сразу стоит учесть, что файл изображения будет добавляться в приложение, тем самым увеличивая его размер. Кроме того, большие изображения отрицательно влияют на производительность. Поэтому лучше использовать небольшие и оптимизрованные (сжатые) графические файлы. Хотя, также стоит отметить, что все файлы изображений, которые добавляются в эту папку, могут автоматически оптимизироваться с помощью утилиты aapt во время построения проекта. Это позволяет уменьшить размер файла без потери качества.

При копировании файла нам будет предложено установить для него новое имя.

Можно изменить название файла, а можно оставить так как есть. В моем случае файл называется dubi2.png . И затем нажмем на кнопку Refactor. И после этого в папку drawable будет добавлен выбранный нами файл изображения.

Для работы с изображениями в Android можно использовать различные элементы, но непосредственно для вывода изображений предназначен ImageView . Поэтому изменим файл activity_main.xml следующим образом:

В данном случае для отображения файла в ImageView у элемента устанавливается атрибут android:src . В его значении указывается имя графического ресурса, которое совпадает с именем файла без расширения. И после этого уже в Preview или в режиме дизайнере в Android Studio можно будет увидеть применение изображения, либо при запуске приложения:

Если бы мы создавали ImageView в коде java и из кода применяли бы ресурс, то activity могла бы выглядеть так:

В данном случае ресурс drawable напрямую передается в метод imageView.setImageResource() , и таким образом устанавливается изображение. В результате мы получим тот же результат.

Однако может возникнуть необходимость как-то обработать ресурс перед использованием или использовать его в других сценариях. В этом случае мы можем сначала получить его как объект Drawable и затем использовать для наших задач:

Для получения ресурса применяется метод ResourcesCompat.getDrawable() , в который передается объект Resources, идентификатор ресурса и тема. В данном случае тема нам не важна, поэтому для нее передаем значение null. Возвращается ресурс в виде объекта Drawable :

Затем, например, можно также передать ресурс объекту ImageView через его метод setImageDrawable()

Источник

Android drawable from resource file

Android Drawable Resources Tutorial

A drawable resource represents a graphic file or xml drawable file that can be drawn on screen. In Android, these files are stored in res/drawable folder. To prevent blurred images, drawable resources for different screen resolutions are provided in screen resolution specific drawable folders such as drawable-mdpi, drawable-hdpi, drawable-xhdpi and drawable-xxhdpi. Please see providing and accessing android resources for more information about alternate android resources.

Different types of drawables are bitmap, xml bitmap, nine-patch, layer list, state list, level list, transition drawable, clip drawable, scale drawable and shape drawable.

Bitmap

Bitmap files are .png, .jpg and .gif. The preferred bitmap file for android is .png. Bitmap file needs to be saved in res/drawable folder and can be accessed from xml and java code. For example if you save a bitmap file panda.png in your project, you can access from xml and java code as shown below.

Bitmap file can be read as Drawable object using Resources object.

XML Bitmap

You can add properties to bitamp in xml and use it as drawable. Some properties which can be added to bitmap are dither, used when image and screen pixel don’t match, filter, used to smooth bitmap appearance when it’s stretched or shrunken, and tile mode, used to repeat the image. Below is an example xml bitmap with tileMode set to mirror.

Читайте также:  Mcafee android полная версия

If a bitmap is smaller than its container, you can specify the position of drawable in its container using gravity attribute. Gravity attribute values such as top, bottom, left, right and center won’t scale bitmap if it is smaller than the container view.

Used it as image view background.

Nine-Patch File

Similar to bitmap, you can use nine-patch files and nine-patch xml. Please see create 9-patch file to know how to convert bitmap into nine-patch image file

Layer List

You can define a list of drawables in xml and use it as drawable resource in your android app. This drawable is called layer list drawable. Layer list drawable draws drawable items in the order they are defined in the xml and each drawable item is drawn on top of previous drawable item. The last drawable item is drawn on the top.

The root element of layer list drawable xml is layer-list element, you can define layers of drawable items using item element. Below is an example of layer list drawable.

Layer list drawable is used as value of src attribute of ImageView.

State List

State list drawable allows you to define list of drawables for different states of a view. When state list drawable is set to one of the drawable attributes of a view, the attribute’s value is derived from the state list drawable xml for the current state of the view. As view’s state changes, value for the attribute will change to the drawable defined in the state list drawable xml for the changed state.

Root element of state list drawable xml is selector. You define drawable item for each state using item element. View states are focused, selected, pressed, hovered, checkable, clicked, enabled and activated.

Below is an example of state list drawable xml which can be used in styles as value for button attribute for checkbox. Please see custom checkbox example for more information.

Level List

Using level list drawable, drawable attributes of a view can be set to deferent drawables at run time by calling setLevel on Drawable object and passing level value to it. The level value points to a drawable in the level list drawable.

You can define level list drawable xml with different drawable items setting max and min values for each drawable. At run time, depending on the value passed to setLevel method, a drawable from the level drawable list will be picked and displayed.

Below example defines level list xml with three dawable items with different levels and level ranges. On clicking a button, level is incremented by calling setLevel on Drawable that will make it show corresponding drawable from the level list. Every time the button is clicked, image will be changed to reflect level value.

Transition Drawable

Transition drawable allows you to define two drawable items in xml and it transitions from first drawable to second drawable on calling startTransition method on it. You can specify transition time as an argument to startTransition method. To make it transition from second drawable item to first drawable, method reverseTransition needs to be called. In the below example, every time a button is clicked, image transition will occur.

Inset Drawable

You can use inset drawable when the drawable is smaller than View to make it visible.

Clip Drawable

Clip drawable allows you to hide a drawable and slowly make it visible. By calling setLevel on drawable object and increasing the level will reveal the image slowly as the level increases. In the below example as button is clicked, image will be slowly visible.

Scale Drawable

Using scale drawable, you can specify how a drawable can be scaled depending on the level by setting scale height, scale width and scale gravity. Below is an example scale drawable which is displayed in image view. On clicking a button, the drawable’s level will be increased by calling setLevel and passing level. As the level increases, the drawable that is displayed in ImageView will scale.

Shape Drawable

Shape drawable allows you to define different shapes in xml and the defined xml can be used as value of drawable attributes of views. You can define rectangle, square, oval and ring shapes using shape drawable. For more information on shape drawables, please see shape drawable examples.

About

Android app development tutorials and web app development tutorials with programming examples and code samples.

Источник

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