Как сделать градиент в андроид студио
Перейти к содержимому

Как сделать градиент в андроид студио

  • автор:

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

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

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

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

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

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

  • xmlns:android — обязательный атрибут со строкой "http://schemas.android.com/apk/res/android"
  • android:shape — задаёт тип фигуры: rectangle (прямоугольник, заполняющий элемент, является фигурой по умолчанию), oval (овал), line (линия, требуется также наличие элемента <stroke> для задания ширины линии), ring (окружность, для данной фигуры можно использовать атрибуты android:innerRadius, android:innerRadiusRatio, android:thickness, android:thicknessRatio, android:useLevel)
  • <corners> — создаёт закругленные углы для фигуры. Только для прямоугольника. Возможные атрибуты: android:radius, android:topLeftRadius, android:topRightRadius, android:bottomLeftRadius, android:bottomRightRadius
  • <gradient> — задаёт градиентную заливку для фигуры. Возможные атрибуты: android:angle, android:centerX, android:centerY, android:centerColor, android:endColor, android:gradientRadius, android:startColor, android:type, android:useLevel
  • <padding> — отступы. Возможные атрибуты: android:left, android:top, android:right, android:bottom
  • <size> — размеры фигуры. Возможные атрибуты: android:height, android:width
  • <solid> — сплошной цвет для фигуры. Возможные атрибуты: android:color
  • <stroke> — контур фигуры. Возможные атрибуты: android:width, android:color, android:dashGap (расстояние между черточками), android:dashWidth (длина пунктирной черточки)

rectangle (Прямоугольник)

rectangle

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

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

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

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

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

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

Rounded rectangle

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

rectangles

rectangle_rounded_some.xml

oval (Эллипс)

shape_oval.xml

oval

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

Oval

ring (Кольцо)

ring

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

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

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

line

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

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

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

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

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

linear

Linear Gradient

gradient_linear.xml

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

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

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

radial

  • android:gradientRadius является обязательным для радиального градиента, а у остальных игнорируется. Рисует круговой градиент, начиная с цвета startColor и заканчивая endColor, от внешнего края фигуры до её центра (ещё есть centerColor). Атрибут gradientRadius указывает радиус градиентного перехода в пикселях. Поскольку радиус градиента указывается в пикселях, он не будет автоматически масштабироваться при разной плотности точек на экране. Чтобы минимизировать эффект ступенчатости, необходимо указывать разные значения радиуса для дисплеев с разным разрешением.
  • Имеются также необязательные атрибуты android:centerX и android:centerY, в которых можно задавать относительное (0.0 – 1.0), описывающие сдвиг центральной точки градиента.

gradient_radial.xml

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

Radial Gradient

sweep

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

Sweep Gradient

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

gradient_sweep.xml

gradient_circle.xml

Sweep Gradient

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

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

Примеры с shape

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

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

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

Round Rect

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

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

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

How to make gradient background in android

I want to create gradient background where the gradient is in the top half and there’s a solid color in the bottom half, like in this image below:

I can’t because the centerColor spreads out to cover the bottom and top.

In the gradient for the button, a white horizontal line fades over blue toward the top and botton.

How can I make a background like the first image? How can I make small centerColor that’s not spread out?

The Guide to Color Gradients in Android Studio

Adjusting the background color of your activities and fragments is one of the easiest ways to add flair to your mobile apps. A strong color palette can make a bad app okay and a good app great if applied with artistic tenderness. In this article, I’m going to explore one component of the tender artist’s toolkit: the gradient. I’ll also go one step further and illustrate how a gradient can be animated on screen automatically or with respect to some other value.

Gradient Drawable in Android — Create Gradient Backgrounds

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.

gradient background in Android app

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 <gradient> drawable:

Start color of the gradient.

The value of color may be in any one of «#rgb», «#argb», «#rrggbb», «#aarrggbb» forms

End color of the gradient

The value of color may be in any one of «#rgb», «#argb», «#rrggbb», «#aarrggbb» forms

The Center color of the gradient. It may be optional but you can use it if you want

The value of color may be in any one of «#rgb», «#argb», «#rrggbb», «#aarrggbb» forms

X position of the center point of the gradient within the shape as a fraction of the width

0.5 is the default value

Y-position of the center point of the gradient within the shape as a fraction of the height

0.5 is the default value

The angle of the gradient and it is only used with the linear gradient

It must be multiple of 45 in the range [0, 315]

It is used to set the type of gradient and the default value is linear . and it is of 3 types

It is used to set the radius of the gradient. It is only used with the radial gradient.

Step 3: Modify activity_main.xml

Now open the activity_main.xml file and remove the default code and change the layout to RelativeLayout and set it’s background to gradient background as shown below:

with this our activity_main.xml is done and the complete code will look like:

And the output of the above is shown below:

gradient background in Android App

We can also add the gradient to different Views and layouts in our Android App. Let’s cover a few other Android App components in which we can use gradient backgrounds.

Gradient background with Button:

Here we will use the gradient background for button:

Output of the above code is:

gradient background in Android App

Gradient background with TextView:

Here we will use the gradient background for TextView:

The output of the above code is:

gradient background in Android App

Gradient background with ImageView:

Here we will use the gradient background for ImageView:

The output of the above code is:

gradient background in Android App

Gradient background with SeekBar:

Here we will use the gradient background for SeekBar:

The output of the above code is:

gradient background in Android App

Conclusion:

In just 3 simple steps we have integrated and shown you the basic example for creating a Gradient Drawable in your android app. If you face any issue while doing this, please share it in the comment section below and we will be happy to help.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *