Android studio xml drawable

Drawable. Фигуры и градиенты

Shape и ShapeDrawable

Фигуры являются подмножеством Drawable-ресурсов.

Данный вид ресурсов на основе класса ShapeDrawable позволяет описывать простые геометрические фигуры, указывая их размеры, фон и контур с помощью тега .

Можно создавать ресурсы фигур на основе стандартных фигур вроде прямоугольника, эллипса, линии. Для использования ресурсов фигур нужно создать в подкаталоге res/drawable XML-файл, в котором будет присутствовать тег , который в свою очередь может содержать дочерние элементы , ,

Имя файла без расширения будет служить идентификатором (ID): R.drawable.filename в Java-коде и @[package:]drawable/filename в XML-файлах.

Элементы фигуры

— отступы. Возможные атрибуты: android:left, android:top, android:right, android:bottom

  • — размеры фигуры. Возможные атрибуты: android:height, android:width
  • — сплошной цвет для фигуры. Возможные атрибуты: android:color
  • — контур фигуры. Возможные атрибуты: android:width, android:color, android:dashGap (расстояние между черточками), android:dashWidth (длина пунктирной черточки)
  • rectangle (Прямоугольник)

    shape_rect.xml — Атрибут android:shape здесь необязателен: rectangle — это значение по умолчанию.

    Пример с градиентным прямоугольником в качестве разделителя

    Создадим файл separator.xml:

    В разметке приложения добавим код:

    У первого разделителя ширина 1dp, у второго — 3dp. Получили красивую полоску.

    У прямоугольников можно скруглить углы при помощи тега corners

    Можно закруглить углы по отдельности:

    oval (Эллипс)

    Другой вариант с пунктиром:

    ring (Кольцо)

    shape_ring.xml — Для кольца имеются дополнительные атрибуты:

    innerRadius Внутренний радиус innerRadiusRatio Отношение между внешним и внутренним радиусами. По умолчанию равно 3 thickness Толщина кольца (т.е. разница между внешним и внутренним радиусами) thicknessRatio Отношение ширины кольца к его толщине. По умолчанию равно 9

    line (Горизонтальная линия)

    shape_line.xml — Линия может быть только горизонтальной

    Градиенты: gradient и GradientDrawable

    Тег gradient (класс GradientDrawable) позволяет создавать сложные градиентные заливки. Каждый градиент описывает плавный переход между двумя или тремя цветами с помощью линейного/радиального алгоритма или же используя метод развертки.

    Тег gradient внутри тега shape. Основные атрибуты: type, startColor (обязателен), endColor (обязателен) и middleColor (необязателен). Также иногда оказывается полезным атрибут centerColor.

    Используя атрибут type, вы можете описать свой градиент:

    linear

    • android:type=»linear» можно опустить, он так и есть по умолчанию. Отображает прямой переход от цвета startColor к цвету endColor под углом, заданным в атрибуте angle.
    • Атрибут android:angle используется только линейным градиентом и должен быть кратным значению 45.

    Дополнительный материал: Android Dev Tip #3 — помните о прозрачности, который может привести к другому результату.

    Также можно задействовать атрибуты centerX и centerY.

    radial

    Интересный эффект получается при использовании множества радиальных градиентов.

    sweep

    Рисует развёрточный градиент с помощью перехода между цветами startColor и endColor вдоль внешнего края фигуры (как правило, кольца).

    Можно использовать атрибуты android:centerX и android:centerY.

    Попробуйте также такой вариант.

    А почему бы не повращать?

    Примеры с shape

    Закругляем уголки у компонентов

    Создадим отдельный файл res/drawable/roundrect.xml и с его помощью скруглим уголки у LinearLayout, ImageView, TextView, EditText:

    В разметке активности пишем следующее:

    Овальный кабинет

    В Белом доме есть Овальный кабинет. Если вам придётся писать приложение для администрации президента США, то все элементы нужно сделать овальными. Создадим файл res/drawable/oval.xml:

    Читайте также:  Android tv телеканалы 4pda

    Заменим в предыдущем примере android:background=»@drawable/roundrect» на android:background=»@drawable/oval».

    Источник

    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.

    Читайте также:  Joycasino рабочее зеркало для андроид

    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.

    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.

    Источник

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