- Drawable. Фигуры и градиенты
- Shape и ShapeDrawable
- Элементы фигуры
- rectangle (Прямоугольник)
- oval (Эллипс)
- ring (Кольцо)
- line (Горизонтальная линия)
- Градиенты: gradient и GradientDrawable
- linear
- radial
- sweep
- Примеры с shape
- Закругляем уголки у компонентов
- Овальный кабинет
- Android Shape Drawables Tutorial
- Have you ever wanted to reduce your Android application’s size or make it look more interesting? If yes, then you should try out ShapeDrawables.
- Why should you use ShapeDrawables?
- Are there any disadvantages?
- Let’s start coding
- Create a simple gradient ShapeDrawable in XML
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
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:background=»@drawable/roundrect» на android:background=»@drawable/oval».
Источник
Android Shape Drawables Tutorial
Nov 3, 2017 · 6 min read
Have you ever wanted to reduce your Android application’s size or make it look more interesting? If yes, then you should try out ShapeDrawables.
First, we will go over the advantages and disadvantages of the ShapeDrawables. Then we will create some Drawables that could be used in your app and lastly for the grand finale we will try to replicate a gradient as can be seen in the Spotify app/website.
Why should you use ShapeDrawables?
When you want to use PNG or JPEG images in your applic a tion, you have to provide multiple copies of the same image for different screen densities. That, of course, clutters your app with copies of the same image. Yes, sometimes that is the path we have to choose because we can’t use Drawables for every single case, but we can dramatically reduce our application’s size if we can use Drawables instead. ShapeDrawables are a series of commands that tell how to draw something on the screen. That is why they can be resized and stretched as much as we want, without losing any quality. We can recolor and manipulate them even when the app is running and use the same ShapeDrawable multiple times in our app. Since ShapeDrawables are a subclass of the Drawable abstract class, we can use them in methods where a Drawable is expected. Click for the documentation of the ShapeDrawable.
Are there any disadvantages?
Of course, just like I have mentioned before we can’t use them in every case. I have said before that ShapeDrawable class is a subclass of the Drawable abstract class. There are other subclasses as well and every one of them has its own use case. You can click here to check other Drawable types and figure out which one is right for your case. Another issue is that they took a bit longer to draw than a Bitmap since there is a lot of parsing and drawing going on behind the scenes. But I think that is not a huge problem if your Drawables are simple.
My opinion is that you should use Drawables (ShapeDrawables) wherever you can, because they are easy to modify and they don’t take much space.
Let’s start coding
First let’s take a look at a simple example and then we will recreate a gradient as can be seen in the Spotify app/website.
Create a simple gradient ShapeDrawable in XML
First create a new drawable resource file.
Right click on res/drawable > New > Drawable resource file > give your file a name > use shape as a root element > click Ok
Shape root element defines that this is a ShapeDrawable.
This is how the first example looks like:
Источник