- Drawable. Фигуры и градиенты
- Shape и ShapeDrawable
- Элементы фигуры
- rectangle (Прямоугольник)
- oval (Эллипс)
- ring (Кольцо)
- line (Горизонтальная линия)
- Градиенты: gradient и GradientDrawable
- linear
- radial
- sweep
- Примеры с shape
- Закругляем уголки у компонентов
- Овальный кабинет
- Gradient Text
- Gradient Drawable in Android — Create Gradient Backgrounds
- What is Gradient?
- Step 1: Create a new Project
- Step 2: Creating Gradient Color
- XML attributes of Gradient Drawable
- Step 3: Modify activity_main.xml
- Gradient background with Button:
- Gradient background with TextView:
- Gradient background with ImageView:
- Gradient background with SeekBar:
- Conclusion:
- Полный список
- Кольцо
- GradientDrawable
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».
Источник
Gradient Text
Recently there was a comment on the article on Text Shadows asking how to fill text with a gradient. In this article we’ll look at a simple technique for doing precisely that.
Creating text filled with a gradient is actually really easy, although it’s not immediately obvious how to do it in the same was as simply changing the text colour. The trick is to use a Shader, or more specifically a LinearGradient (which extends Shader), to do all of the work for us.
The constructor for LinearGradient that we’ll use takes seven arguments, although there is also a more complex form which allows for multiple colour steps to be defined. The first four of these represent the start x & y and end x & y coordinates of the line along which the gradient will be drawn (this effectively controls the direction of the gradient). The next two arguments represent the start and end colours of the gradient, and the final argument dictates how areas outside of the rectangle defined in the first four arguments will be drawn.
So how do we go about applying this? In its simplest form, we can get a reference to a standard TextView object, and set the Shader on it’s Paint object:
The TileMode that we’re using means that the colour of areas outside of the rectangle (0, 0) – (0, 100) will match the colour of the closest edge of that rectangle – i.e. extending the colour of the edges of the rectangle.
While this will certainly work, it does suffer from the small drawback that the gradient will need to be static dimensions which are completely detached from the size of the text within the TextView. So what if we want the dimensions of the gradient to actually match our text? We simply need to extend TextView.
Now the obvious thought is to extend TextView and simply override onDraw() to create a new LinearGradient which matches the dimensions of the textView control each time the control is drawn. However this is rather inefficient because it means instantiating a Shader object each time onDraw is called. Object instantiation is a rather expensive business and should be avoided at all costs in your onDraw method. If you perform object instantiation in your onDraw you’ll find that your frame rates suffer badly as a result.
So if we don’t do it in onDraw, then where should we do it? The answer is quite obvious when we think about how often we actually need to create a new LinearGradient: only when the size of the TextView changes. Therefore, the most efficient place to do this is actually in onLayout:
Источник
Gradient Drawable in Android — Create Gradient Backgrounds
LAST UPDATED: AUGUST 10, 2021
We have seen the Gradient colors on many websites as backgrounds, used in App logos, like in the Instagram logo shown below, App background, buttons, progress bars, etc. A gradient makes the UI of any app, be it Mobile App or a website, more beautiful and vibrant. Many developers are using gradient in their apps and websites to make it look more attractive. So in this tutorial, we will learn how to set a gradient background for our Android App activity.
What is Gradient?
According to Wikipedia:
In computer graphics, a color gradient specifies a range of position-dependent colors, usually used to fill a region. For example, many window managers allow the screen background to be specified as a gradient. The colors produced by a gradient vary continuously with the position, producing smooth color transitions.
A color gradient is also known as a color ramp or a color progression. In assigning colors to a set of values, a gradient is a continuous colormap, a type of color scheme.
So let’s add a simple gradient to our Android App.
Step 1: Create a new Project
Open Your Android Studio Click on «Start a new Android Studio project» (Learn how to setup Android Studio and create your first Android project)
Choose «Empty Activity» from the project template window and click Next
Enter the App Name, Package name, save location, language(Java/Kotlin, we use Java for this tutorial), and minimum SDK(we are using API 19: Android 4.4 (KitKat))
Next click on the Finish button after filling the above details
Now, wait for the project to finish the build.
Step 2: Creating Gradient Color
To create a gradient color we need to create a .xml file in the drawable folder. So go to app -> res -> drawable and right-click on drawable -> New -> Drawable Resource File and create gradient_drawable.xml file.
The code of gradient_drawable.xml file is shown below:
As you can see in the code above, we are using the gradient tag along with providing android:startColor , android:centerColor and android:endColor attributes to define the color that will be used in the gradient. So let’s learn about the attributes available in the gradient drawable.
XML attributes of Gradient Drawable
Following are the attributes of the drawable:
Attributes | Description |
---|---|
android:startColor |