- Drawable. Фигуры и градиенты
- Shape и ShapeDrawable
- Элементы фигуры
- rectangle (Прямоугольник)
- oval (Эллипс)
- ring (Кольцо)
- line (Горизонтальная линия)
- Градиенты: gradient и GradientDrawable
- linear
- radial
- sweep
- Примеры с shape
- Закругляем уголки у компонентов
- Овальный кабинет
- Android Material Components: Exploring MaterialShapeDrawable
- What is MaterialShapeDrawable ?
- Introducing ShapeAppearanceModel
- Corners
- Edges
- Animations
- XML usage with Material Theming
- The shapeAppearance attribute
- Wrap-up
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 Material Components: Exploring MaterialShapeDrawable
Material Components is the (not so) new library made by the Material team to replace the old support design library.
It provides components to apply Material Design in your application with ease. Among these components, you can find the famous FloatingActionButton , the CardView or the BottomSheet .
But there are also some less known, nonetheless powerful, components. And one of them is the MaterialShapeDrawable .
Note: This article was written using the version 1.1.0-alpha07> of the Material Components.
MaterialShapeDrawable existed in the 1.0.0 stable but the API changed quite a lot in the version 1.1.0-alpha01.
What is MaterialShapeDrawable ?
According to the documentation:
Base drawable class for Material Shapes that handles shadows, elevation, scale and color for a generated path.
And by Shape , they are referring to the Material Guidelines shapes: Rectangular shapes with curved or angled edges and/or corners…
In the build.gradle of your app, add the new dependency (or update it if you already use Material Components)
We will start by creating a new MaterialShapeDrawable and setting it as the background of a TextView .
The drawable supports a couple of customizations like:
If your view has elevation, a shadow will be cast on API above 21 like any other drawable. But this drawable supports a compatibility version of shadows for devices running API lower than 21. In this case, you need to specify the elevation on the drawable itself:
For now, this provides nothing more that a simple ShapeDrawable couldn’t do, apart from the compatibility shadows. So what’s the point?
Introducing ShapeAppearanceModel
A ShapeAppearanceModel is a model of edges and corners used by a MaterialShapeDrawable to render itself. Every MaterialShapeDrawable has a ShapeAppearanceModel .
The default ShapeAppearanceModel has 4 rounded corners with a 0px radius and 4 flat edges. And of course, you can customize it in order to provide your own model:
Corners
ShapeAppearanceModel has two out-of-the-box types of corners: rounded and cut.
8dp rounded corners
8dp cut corners
You can change all 4 corners at once:
Or you can change each corner individually:
different corners with strokes
You can also create your own corners. ShapeAppearanceModel uses a CornerTreatment object for each corner. The previously shown ways of customizing the corners were just shortcuts to build instances of CutCornerTreatment and RoundedCornerTreatment .
You can also write your own implementation of CornerTreatment if cut or rounded corners are not enough for you.
For example, if you want an inside cut corner, you could use this implementation of CornerTreatment :
The interpolation parameter is used for animations. Its value ranges from 0 to 1 and it’s used to compute the current radius of the corner. More example are shown later in this article.
And apply it to your ShapeAppearanceModel :
Edges
Edges are handled the same way as corners, by giving to the model instances of EdgeTreatment objects.
There is only one built-in edge treatment: the TriangleEdgeTreatment . It draws a triangle facing in or out of the shape in the middle of an edge.
This can be useful to add nice looking tooltips into your app.
Like for corners, you can build custom edge treatments.
You can find a very good example in the code of the BottomAppBar of the material components.
The BottomAppBar is using a MaterialShapeDrawable and the cradle for the FAB is a custom EdgeTreatment.
Animations
MaterialShapeDrawable supports animation of its treatments, whether it’s edge or corner, via the interpolation parameter. This attribute is ranging from 0 to 1. At 0, the treatments are not rendered at all (this results in square corners and flat edges). At 1, they are fully rendered.
When building custom treatments, be aware of the interpolation parameter of getCornerPath method as this is the current interpolation of the drawable and you should take it into account when building the ShapePath of your treatment.
In this example, the interpolation property is either animated with an ObjectAnimator , or modified by the tracking of a SeekBar .
XML usage with Material Theming
The shapeAppearance attribute
If you dug a bit in the source code of MaterialShapeDrawable , you probably noticed that this component supports XML inflation, but in a special way.
You can leverage it by using Material components widgets that are using MaterialShapeDrawable internally:
- BottomSheet
- Chip
- MaterialButton (and subclasses like ExtandedFloatingActionButton )
- FloatingActionButton
- MaterialCardView
- TextInputLayout
On all theses widgets, you can use the
attribute and pass it a reference to a style containing the attributes of your custom appearance.
Here is a list of all supported attributes to customize the appearance :
- cornerFamily (values: rounded or cut)
- cornerFamilyTopLeft
- cornerFamilyTopRight
- cornerFamilyBottomRight
- cornerFamilyBottomLeft
- cornerSize (dimension)
- cornerSizeTopLeft
- cornerSizeTopRight
- cornerSizeBottomRight
- cornerSizeBottomLeft
If you want to implements the shape of the Shrine Material Studies, you can simply write:
You can change the shape of any supported widgets without writing code.
But it can be tedious to remember to always specify the shapeAppearance if you want all your widgets to have the same shape.
Fortunately, with the new Material Themes, you can control the default shape of all the Material widgets.
There are 3 new theme attributes to control the default shapes:
- shapeAppearanceSmallComponent
- used by:
- Chip
- MaterialButton (and ExtendedFloatingActionButton )
- FloatingActionButton
- TextInputLayout
- the items of NavigationView
- used by:
- shapeAppearanceMediumComponent
- used by:
- MaterialCardView
- used by:
- shapeAppearanceLargeComponent
- used by:
- BottomSheet
- used by:
By settings those attributes in your theme to a custom ShapeAppearance Style, every widgets impacted will be automatically properly shaped.
How does it work internally? The default style of these widgets all include a shapeAppearance attribute referencing one of the 3 theme attributes. You can see an example for MaterialButton in the source code.
If you want to learn more about how all the theming, styling and default attributes work, you can read Android Styles & Themes for developers.
Here is how you would customise all the shapes of you app using Material Theming:
We can observe that some widgets like the Chip or the FloatingActionButton override the cornerSize of the theme. For the FAB, the cornerSize will be computed to always be 50% of the size of the fab.
Wrap-up
MaterialShapeDrawable is a very powerful tool used a lot across the Material Components library.
You have learned how to use it directly in code to build very specific shapes and you also learned how to use it in your layout files and to customise your app theme to globally change all the shapes of your application.
Material Components are open-source and you can find the code on Github.
If you want to go further with Material Theming (colors, typography etc…), I highly recommend Styles, Themes, Material Theming, Oh My! by Anita Singh.
I hope you will have fun experiencing with it in your own apps!
Источник