Как добавить картинку в андроид студио

от admin

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

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

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

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

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

Добавление изображений в папку drawable Android Studio

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

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

Ресурсы drawable в Android и Java

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

Добавление изображений в Android Studio

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

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

ImageView и drawable в Android Studio и Java

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

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

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

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

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

How to add an image to the "drawable" folder in Android Studio?

When I choose new > Image Asset , it comes out a dialog to choose Asset Type .

How can I add an image to res/drawable folder?

live-love's user avatar

Alan W.'s user avatar

23 Answers 23

For Android Studio 1.5:

  1. Right click on res -> new ->Image Asset
  2. On Asset type choose Action Bar and Tab Icons
  3. Choose the image path
  4. Give your image a name in Resource name
  5. Next -> Finish

Update for Android Studio 2.2:

Right click on res -> new -> Image Asset

On Icon Type choose Action Bar and Tab Icons

On Asset type choose Image

On Path choose your image path

The image will be saved in the /res/drawable folder.

Warning! If you choose to use images other than icons in SVG or PNG be aware that it could turn grey if the image is not transparent. You can find an answer in comments for this problem but none of these are verified by me because I never encountered this problem. I suggest you to use icons from here: Material icons

RBT's user avatar

Chris's user avatar

For Android Studio 3.4+:

You can use the new Resource Manager tab Click on the + sign and select Import Drawables .

From here, you can select multiple folders/files and it will handle everything for you.

Resource Manager

The result will look something like this:

Resource Manager Picker

Click the import button and the images will be automatically imported to the correct folder.

RBT's user avatar

Copy *.png image and paste to drawable folder.

After adding the image, you can use the added image asset in code:

You can either add image by using xml file

OR You can set image by using program:

RBT's user avatar

Arshid KV's user avatar

Do it through the way Android Studio provided to you

Right click on the res folder and add your image as Image Assets in this way. Android studio will automatically generate image assets with different resolutions.

You can directly create the folder and drag image inside but you won’t have the different sized icons if you do that.

For Example, I’ve to add list.png in drawable folder..

enter image description here

And now I’ll paste it in drawable folder. Alternatively you can do it Ctrl + C / V , as we programmers do it. 🙂

enter image description here

RBT's user avatar

Saim Mehmood's user avatar

It’s very simple. Just copy your image and paste it in the drawable folder. One more thing. When you paste an image in the drawable folder, a popup window will appear asking for a folder name. Add xxhdpi,xhdpi,hdpi or mdpi according to your image, like in the image below:enter image description here

If you are still having problems, check out this link: Drawable folder in android studio

kundan roy's user avatar

You can just copy and paste an image file(.jpg at least) into your res/drawable. It worked for me!

Open your project in Android Studio

Right click on drawable

Click on Show in Explorer

Double click on drawable folder.

Copy your image file in it and rename as your wish.

Now write your image file name after @drawable/ .

It will show the image you’ve selected.

Spikatrix's user avatar

Install and use the Android Drawable Importer plugin:

Instructions on how to install the plugin are on that page. It’s called «Android Drawable Importer» in the plugin search results.

  1. right click on «res» folder and select New -> Batch Drawable Import
  2. hit the + and select your source image
  3. choose what resolution you want it considered and which other sizes to auto-generate for

Seems kind of ridiculous that Android Studio doesn’t support this directly.

EDIT: But Xcode doesn’t either so. 🙁

You need to use a third party plugin like AndroidIcons Drawable Import to install this. Goto Android Studio > Prefrences > Plugins > and browse for AndroidIcons Drawable You can do things like

  1. AndroidIcons Drawable Import
  2. Material Icons Drawable Import
  3. Scaled Drawable
  4. Multisource-Drawable

Restart android studio. If you do not have the drawables folder created, create it by importing any image as -«Action Bar and Tab Icons» & «Notification Icons»,. Then right clink on the file explorer and you can see 4 options in the new tab. Use any one according to your need.

Drawable resources

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 , .webp , .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 drawable 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 GradientDrawable .

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 the following formats: .png (preferred), ,webp (preferred, requires API level 17 or higher), .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 , .webp , .jpg , or .gif file. Android creates a Drawable resource for any of these files when you save them in the res/drawable/ directory.

The following application code retrieves the image as a Drawable :

Kotlin

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 <bitmap> element as a child of an <item> element. For example, when creating a state list or layer list, you can exclude the android:drawable attribute from an <item> element and nest a <bitmap> inside it that defines the drawable item.

xmlns:android String. Defines the XML namespace, which must be «http://schemas.android.com/apk/res/android» . This is required only if the <bitmap> is the root element—it is not needed when the <bitmap> is nested inside an <item> . 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.

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:

  • 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 accommodate 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: <nine-patch> 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 <item> element inside a single <layer-list> element.

file location: res/drawable/filename.xml
The filename is used as the resource ID. compiled resource datatype: Resource pointer to a LayerDrawable . resource reference: In Java: R.drawable.filename
In XML: @[package:]drawable/filename syntax: elements: <layer-list> Required. This must be the root element. Contains one or more <item> elements.

xmlns:android String. Required. Defines the XML namespace, which must be «http://schemas.android.com/apk/res/android» . <item> Defines a drawable to place in the layer drawable, in a position defined by its attributes. Must be a child of a <layer-list> element. Accepts child <bitmap> elements.

android:drawable Drawable resource. Required. Reference to a drawable resource. android:id Resource ID. A unique resource ID for this drawable. To create a new resource ID for this item, use the form: «@+id/name» . The plus symbol indicates that this should be created as a new ID. You can use this identifier to retrieve and modify the drawable with View.findViewById() or Activity.findViewById() . android:top Dimension. The top offset, as a dimension value or dimension resource. android:right Dimension. The right offset, as a dimension value or dimension resource. android:bottom Dimension. The bottom offset, as a dimension value or dimension resource. android:left Dimension. The left offset, as a dimension value or dimension resource.

All drawable items are scaled to fit the size of the containing View, by default. Thus, placing your images in a layer list at different positions might increase the size of the View and some images scale as appropriate. To avoid scaling items in the list, use a <bitmap> element inside the <item> element to specify the drawable and define the gravity to something that does not scale, such as «center» . For example, the following <item> defines an item that scales to fit its container View:

To avoid scaling, the following example uses a <bitmap> element with centered gravity:

example: XML file saved at res/drawable/layers.xml :

Notice that this example uses a nested <bitmap> element to define the drawable resource for each item with a «center» gravity. This ensures that none of the images are scaled to fit the size of the container, due to resizing caused by the offset images.

This layout XML applies the drawable to a View:

The result is a stack of increasingly offset images:

State list

A StateListDrawable is a drawable object defined in XML that uses a several different images to represent the same graphic, depending on the state of the object. For example, a Button widget can exist in one of several different states (pressed, focused, or neither) and, using a state list drawable, you can provide a different background image for each state.

You can describe the state list in an XML file. Each graphic is represented by an <item> element inside a single <selector> element. Each <item> uses various attributes to describe the state in which it should be used as the graphic for the drawable.

During each state change, the state list is traversed top to bottom and the first item that matches the current state is used—the selection is not based on the «best match,» but simply the first item that meets the minimum criteria of the state.

file location: res/drawable/filename.xml
The filename is used as the resource ID. compiled resource datatype: Resource pointer to a StateListDrawable . resource reference: In Java: R.drawable.filename
In XML: @[package:]drawable/filename syntax: elements: <selector> Required. This must be the root element. Contains one or more <item> elements.

xmlns:android String. Required. Defines the XML namespace, which must be «http://schemas.android.com/apk/res/android» . android:constantSize Boolean. «true» if the drawable’s reported internal size remains constant as the state changes (the size is the maximum of all of the states); «false» if the size varies based on the current state. Default is false. android:dither Boolean. «true» to enable dithering of the bitmap if the bitmap does not have the same pixel configuration as the screen (for instance, an ARGB 8888 bitmap with an RGB 565 screen); «false» to disable dithering. Default is true. android:variablePadding Boolean. «true» if the drawable’s padding should change based on the current state that is selected; «false» if the padding should stay the same (based on the maximum padding of all the states). Enabling this feature requires that you deal with performing layout when the state changes, which is often not supported. Default is false. <item> Defines a drawable to use during certain states, as described by its attributes. Must be a child of a <selector> element.

Читать:
Seagate или western digital что лучше

android:drawable Drawable resource. Required. Reference to a drawable resource. android:state_pressed Boolean. «true» if this item should be used when the object is pressed (such as when a button is touched/clicked); «false» if this item should be used in the default, non-pressed state. android:state_focused Boolean. «true» if this item should be used when the object has input focus (such as when the user selects a text input); «false» if this item should be used in the default, non-focused state. android:state_hovered Boolean. «true» if this item should be used when the object is being hovered by a cursor; «false» if this item should be used in the default, non-hovered state. Often, this drawable may be the same drawable used for the «focused» state.

Introduced in API level 14.

android:state_selected Boolean. «true» if this item should be used when the object is the current user selection when navigating with a directional control (such as when navigating through a list with a d-pad); «false» if this item should be used when the object is not selected.

The selected state is used when focus ( android:state_focused ) is not sufficient (such as when list view has focus and an item within it is selected with a d-pad).

android:state_checkable Boolean. «true» if this item should be used when the object is checkable; «false» if this item should be used when the object is not checkable. (Only useful if the object can transition between a checkable and non-checkable widget.) android:state_checked Boolean. «true» if this item should be used when the object is checked; «false» if it should be used when the object is un-checked. android:state_enabled Boolean. «true» if this item should be used when the object is enabled (capable of receiving touch/click events); «false» if it should be used when the object is disabled. android:state_activated Boolean. «true» if this item should be used when the object is activated as the persistent selection (such as to «highlight» the previously selected list item in a persistent navigation view); «false» if it should be used when the object is not activated.

Introduced in API level 11.

android:state_window_focused Boolean. «true» if this item should be used when the application window has focus (the application is in the foreground), «false» if this item should be used when the application window does not have focus (for example, if the notification shade is pulled down or a dialog appears).

Note: Remember that Android applies the first item in the state list that matches the current state of the object. So, if the first item in the list contains none of the state attributes above, then it is applied every time, which is why your default value should always be last (as demonstrated in the following example).

example: XML file saved at res/drawable/button.xml :

This layout XML applies the state list drawable to a Button:

Level list

A Drawable that manages a number of alternate Drawables, each assigned a maximum numerical value. Setting the level value of the drawable with setLevel() loads the drawable resource in the level list that has a android:maxLevel value greater than or equal to the value passed to the method.

file location: res/drawable/filename.xml
The filename is used as the resource ID. compiled resource datatype: Resource pointer to a LevelListDrawable . resource reference: In Java: R.drawable.filename
In XML: @[package:]drawable/filename syntax: elements: <level-list> This must be the root element. Contains one or more <item> elements.

xmlns:android String. Required. Defines the XML namespace, which must be «http://schemas.android.com/apk/res/android» . <item> Defines a drawable to use at a certain level.

android:drawable Drawable resource. Required. Reference to a drawable resource to be inset. android:maxLevel Integer. The maximum level allowed for this item. android:minLevel Integer. The minimum level allowed for this item. example:

Once this is applied to a View , the level can be changed with setLevel() or setImageLevel() .

Transition drawable

A TransitionDrawable is a drawable object that can cross-fade between the two drawable resources.

Each drawable is represented by an <item> element inside a single <transition> element. No more than two items are supported. To transition forward, call startTransition() . To transition backward, call reverseTransition() .

file location: res/drawable/filename.xml
The filename is used as the resource ID. compiled resource datatype: Resource pointer to a TransitionDrawable . resource reference: In Java: R.drawable.filename
In XML: @[package:]drawable/filename syntax: elements: <transition> Required. This must be the root element. Contains one or more <item> elements.

xmlns:android String. Required. Defines the XML namespace, which must be «http://schemas.android.com/apk/res/android» . <item> Defines a drawable to use as part of the drawable transition. Must be a child of a <transition> element. Accepts child <bitmap> elements.

android:drawable Drawable resource. Required. Reference to a drawable resource. android:id Resource ID. A unique resource ID for this drawable. To create a new resource ID for this item, use the form: «@+id/name» . The plus symbol indicates that this should be created as a new ID. You can use this identifier to retrieve and modify the drawable with View.findViewById() or Activity.findViewById() . android:top Integer. The top offset in pixels. android:right Integer. The right offset in pixels. android:bottom Integer. The bottom offset in pixels. android:left Integer. The left offset in pixels. example: XML file saved at res/drawable/transition.xml :

This layout XML applies the drawable to a View:

And the following code performs a 500ms transition from the first item to the second:

Kotlin

Inset drawable

A drawable defined in XML that insets another drawable by a specified distance. This is useful when a View needs a background that is smaller than the View’s actual bounds.

file location: res/drawable/filename.xml
The filename is used as the resource ID. compiled resource datatype: Resource pointer to a InsetDrawable . resource reference: In Java: R.drawable.filename
In XML: @[package:]drawable/filename syntax: elements: <inset> Defines the inset drawable. This must be the root element.

Clip drawable

A drawable defined in XML that clips another drawable based on this Drawable’s current level. You can control how much the child drawable gets clipped in width and height based on the level, as well as a gravity to control where it is placed in its overall container. Most often used to implement things like progress bars.

file location: res/drawable/filename.xml
The filename is used as the resource ID. compiled resource datatype: Resource pointer to a ClipDrawable . resource reference: In Java: R.drawable.filename
In XML: @[package:]drawable/filename syntax: elements: <clip> Defines the clip drawable. This must be the root element.

xmlns:android String. Required. Defines the XML namespace, which must be «http://schemas.android.com/apk/res/android» . android:drawable Drawable resource. Required. Reference to a drawable resource to be clipped. android:clipOrientation Keyword. The orientation for the clip.

Must be one of the following constant values:

Value Description
horizontal Clip the drawable horizontally.
vertical Clip the drawable vertically.

android:gravity Keyword. Specifies where to clip within the drawable.

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. When clipOrientation is «vertical» , clipping occurs at the bottom of the drawable.
bottom Put the object at the bottom of its container, not changing its size. When clipOrientation is «vertical» , clipping occurs at the top of the drawable.
left Put the object at the left edge of its container, not changing its size. This is the default. When clipOrientation is «horizontal» , clipping occurs at the right side of the drawable. This is the default.
right Put the object at the right edge of its container, not changing its size. When clipOrientation is «horizontal» , clipping occurs at the left side of the drawable.
center_vertical Place object in the vertical center of its container, not changing its size. Clipping behaves the same as when gravity is «center» .
fill_vertical Grow the vertical size of the object if needed so it completely fills its container. When clipOrientation is «vertical» , no clipping occurs because the drawable fills the vertical space (unless the drawable level is 0, in which case it’s not visible).
center_horizontal Place object in the horizontal center of its container, not changing its size. Clipping behaves the same as when gravity is «center» .
fill_horizontal Grow the horizontal size of the object if needed so it completely fills its container. When clipOrientation is «horizontal» , no clipping occurs because the drawable fills the horizontal space (unless the drawable level is 0, in which case it’s not visible).
center Place the object in the center of its container in both the vertical and horizontal axis, not changing its size. When clipOrientation is «horizontal» , clipping occurs on the left and right. When clipOrientation is «vertical» , clipping occurs on the top and bottom.
fill Grow the horizontal and vertical size of the object if needed so it completely fills its container. No clipping occurs because the drawable fills the horizontal and vertical space (unless the drawable level is 0, in which case it’s not visible).
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.

example: XML file saved at res/drawable/clip.xml :

The following layout XML applies the clip drawable to a View:

The following code gets the drawable and increases the amount of clipping in order to progressively reveal the image:

Kotlin

Increasing the level reduces the amount of clipping and slowly reveals the image. Here it is at a level of 7000:

Note: The default level is 0, which is fully clipped so the image is not visible. When the level is 10,000, the image is not clipped and completely visible.

Scale drawable

A drawable defined in XML that changes the size of another drawable based on its current level.

file location: res/drawable/filename.xml
The filename is used as the resource ID. compiled resource datatype: Resource pointer to a ScaleDrawable . resource reference: In Java: R.drawable.filename
In XML: @[package:]drawable/filename syntax: elements: <scale> Defines the scale drawable. This must be the root element.

xmlns:android String. Required. Defines the XML namespace, which must be «http://schemas.android.com/apk/res/android» . android:drawable Drawable resource. Required. Reference to a drawable resource. android:scaleGravity Keyword. Specifies the gravity position after scaling.

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

Shape drawable

This is a generic shape defined in XML.

file location: res/drawable/filename.xml
The filename is used as the resource ID. compiled resource datatype: Resource pointer to a GradientDrawable . resource reference: In Java: R.drawable.filename
In XML: @[package:]drawable/filename syntax: elements: <shape> The shape drawable. This must be the root element.

xmlns:android String. Required. Defines the XML namespace, which must be «http://schemas.android.com/apk/res/android» . android:shape Keyword. Defines the type of shape. Valid values are:

Value Desciption
«rectangle» A rectangle that fills the containing View. This is the default shape.
«oval» An oval shape that fits the dimensions of the containing View.
«line» A horizontal line that spans the width of the containing View. This shape requires the <stroke> element to define the width of the line.
«ring» A ring shape.

The following attributes are used only when android:shape=»ring» :

android:innerRadius Dimension. The radius for the inner part of the ring (the hole in the middle), as a dimension value or dimension resource. android:innerRadiusRatio Float. The radius for the inner part of the ring, expressed as a ratio of the ring’s width. For instance, if android:innerRadiusRatio=»5″ , then the inner radius equals the ring’s width divided by 5. This value is overridden by android:innerRadius . Default value is 9. android:thickness Dimension. The thickness of the ring, as a dimension value or dimension resource. android:thicknessRatio Float. The thickness of the ring, expressed as a ratio of the ring’s width. For instance, if android:thicknessRatio=»2″ , then the thickness equals the ring’s width divided by 2. This value is overridden by android:innerRadius . Default value is 3. android:useLevel Boolean. «true» if this is used as a LevelListDrawable . This should normally be «false» or your shape may not appear. <corners> Creates rounded corners for the shape. Applies only when the shape is a rectangle.

android:radius Dimension. The radius for all corners, as a dimension value or dimension resource. This is overridden for each corner by the following attributes. android:topLeftRadius Dimension. The radius for the top-left corner, as a dimension value or dimension resource. android:topRightRadius Dimension. The radius for the top-right corner, as a dimension value or dimension resource. android:bottomLeftRadius Dimension. The radius for the bottom-left corner, as a dimension value or dimension resource. android:bottomRightRadius Dimension. The radius for the bottom-right corner, as a dimension value or dimension resource.

Note: Every corner must (initially) be provided a corner radius greater than 1, or else no corners are rounded. If you want specific corners to not be rounded, a work-around is to use android:radius to set a default corner radius greater than 1, but then override each and every corner with the values you really want, providing zero («0dp») where you don’t want rounded corners.

<gradient> Specifies a gradient color for the shape.

android:angle Integer. The angle for the gradient, in degrees. 0 is left to right, 90 is bottom to top. It must be a multiple of 45. Default is 0. android:centerX Float. The relative X-position for the center of the gradient (0 — 1.0). android:centerY Float. The relative Y-position for the center of the gradient (0 — 1.0). android:centerColor Color. Optional color that comes between the start and end colors, as a hexadecimal value or color resource. android:endColor Color. The ending color, as a hexadecimal value or color resource. android:gradientRadius Float. The radius for the gradient. Only applied when android:type=»radial» . android:startColor Color. The starting color, as a hexadecimal value or color resource. android:type Keyword. The type of gradient pattern to apply. Valid values are:

Value Description
«linear» A linear gradient. This is the default.
«radial» A radial gradient. The start color is the center color.
«sweep» A sweeping line gradient.

android:useLevel Boolean. «true» if this is used as a LevelListDrawable . <padding> Padding to apply to the containing View element (this pads the position of the View content, not the shape).

android:left Dimension. Left padding, as a dimension value or dimension resource. android:top Dimension. Top padding, as a dimension value or dimension resource. android:right Dimension. Right padding, as a dimension value or dimension resource. android:bottom Dimension. Bottom padding, as a dimension value or dimension resource. <size> The size of the shape.

android:height Dimension. The height of the shape, as a dimension value or dimension resource. android:width Dimension. The width of the shape, as a dimension value or dimension resource.

Note: The shape scales to the size of the container View proportionate to the dimensions defined here, by default. When you use the shape in an ImageView , you can restrict scaling by setting the android:scaleType to «center» .

<solid> A solid color to fill the shape.

android:color Color. The color to apply to the shape, as a hexadecimal value or color resource. <stroke> A stroke line for the shape.

Android. Вывод изображений, различные способы

Эта статья будет полезна начинающим разработчикам, здесь я предложу несколько вариантов вывода изображений на Android. Будут описаны следующие способы:

Обычный метод – стандартный способ, используя ImageView. Рассмотрены варианты загрузки картинки из ресурса, а также из файла на SD карте устройства.

Продвинутый вариант — вывод изображения, используя WebView. Добавляется поддержка масштабирования и прокрутки картинки при помощи жестов.

“Джедайский” способ – улучшенный предыдущий вариант. Добавлен полноэкранный просмотр с автоматическим масштабированием изображения при показе и поддержкой смены ориентации устройства.

Исходники тестового проекта на GitHub github.com/Voldemar123/andriod-image-habrahabr-example

В этой статье я не рассматриваю вопросы загрузки изображений из Интернета, кеширования, работы с файлами и необходимых для работы приложения permissions – только вывод картинок.

Итак, задача — предположим, в нашем приложении необходимо вывести изображение на экран.
Картинка может размерами превышать разрешение экрана и иметь различное соотношение сторон.
Хранится она либо в ресурсах приложения, либо на External Storage — SD карте.

Также допустим, мы уже записали на карту памяти несколько изображений (в тестовом проекте – загружаем из сети). Храним их в каталоге данных нашего приложения, в кеше.

public static final String APP_PREFS_NAME = Constants.class.getPackage().getName();
public static final String APP_CACHE_PATH =
Environment.getExternalStorageDirectory().getAbsolutePath() +
«/Android/data/» + APP_PREFS_NAME + «/cache/»;

Layout, где выводится картинка

<LinearLayout xmlns:android=»http://schemas.android.com/apk/res/android»
android:layout_width=»match_parent»
android:layout_height=»match_parent»
android:orientation=»vertical» >

<ImageView
android:id=»@+id/imageView1″
android:layout_width=»fill_parent»
android:layout_height=»fill_parent» />

Масштабирование по умолчанию, по меньшей стoроне экрана.
В Activity, где загружаем содержимое картинки

private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageView1);

Из ресурсов приложения (файл из res/drawable/img3.jpg)

Задавая Bitmap изображения

FileInputStream fis = new FileInputStream(Constants.APP_CACHE_PATH + this.image);
BufferedInputStream bis = new BufferedInputStream(fis);

Bitmap img = BitmapFactory.decodeStream(bis);

Или передать URI на изображение (может хранится на карте или быть загружено из сети)

mImageView.setImageURI( imageUtil.getImageURI() );
Uri.fromFile( new File( Constants.APP_CACHE_PATH + this.image ) );

Этот способ стандартный, описан во множестве примеров и поэтому нам не особо интересен. Переходим к следующему варианту.

Предположим, мы хотим показать большое изображение (например фотографию), которое размерами превышает разрешение нашего устройства. Необходимо добавить прокрутку и масштабирование картинки на экране.

<LinearLayout xmlns:android=»http://schemas.android.com/apk/res/android»
android:layout_width=»match_parent»
android:layout_height=»match_parent»
android:orientation=»vertical» >

<WebView
android:id=»@+id/webView1″
android:layout_width=»fill_parent»
android:layout_height=»fill_parent» />

В Activity, где загружаем содержимое

protected WebView webView;
webView = (WebView) findViewById(R.id.webView1);

установка черного цвета фона для комфортной работы (по умолчанию – белый)

включаем поддержку масштабирования

больше места для нашей картинки

webView.setPadding(0, 0, 0, 0);

полосы прокрутки – внутри изображения, увеличение места для просмотра

загружаем изображение как ссылку на файл хранящийся на карте памяти

webView.loadUrl(imageUtil.getImageFileLink() );
«file:///» + Constants.APP_CACHE_PATH + this.image;

Теперь мы хотим сделать так, чтобы картинка при показе автоматически масштабировалась по одной из сторон, при этом прокрутка остается только в одном направлении.
Например, для просмотра фотографий более удобна ландшафтная ориентация устройства.
Также при смене ориентации телефона масштаб изображения должен автоматически меняться.
Дополнительно расширим место для просмотра изображения на полный экран.

В AndroidManifest.xml для нашей Activity добавляем

В код Activity добавлен метод, который вызыватся при каждом повороте нашего устройства.

@Override
public void onConfigurationChanged(Configuration newConfig) <
super.onConfigurationChanged(newConfig);
changeContent();
>

В приватном методе описана логика пересчета масштаба для картинки
Получаем информацию о размерах дисплея. Из-за того, что мы изменили тему Activity, теперь WebView раскрыт на полный экран, никакие другие элементы интерфейса не видны. Видимый размер дисплея равен разрешению экрана нашего Android устройства.

Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

int width = display.getWidth();
int height = display.getHeight();

Размеры изображения, выбранного для показа

Bitmap img = imageUtil.getImageBitmap();

int picWidth = img.getWidth();
int picHeight = img.getHeight();

Меняем масштаб изображения если его высота больше высоты экрана. Прокрутка теперь будет только по горизонтали.

if (picHeight > height)
val = new Double(height) / new Double(picHeight);

Подбрасываем в WebView специально сформированный HTML файл, содержащий изображение.

webView.loadDataWithBaseURL(«/»,
imageUtil.getImageHtml(picWidth, picHeight),
«text/html»,
«UTF-8»,
null);

StringBuffer html = new StringBuffer();

Такой способ я применил из-того, что после загрузки изображения в WebView через метод loadUrl, как в прошлом варианте, setInitialScale после поворота устройства не изменяет масштаб картинки. Другими словами, показали картинку, повернули телефон, масштаб остался старый. Очень похоже на то, что изображение как-то кешируется.

Я не нашел в документации упоминания об этом странном поведении. Может быть местные специалисты скажут, что я делаю не так?

Похожие статьи