Android resource color gradient

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:background=»@drawable/roundrect» на android:background=»@drawable/oval».

    Источник

    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.

    Читайте также:  Где лежит файл hosts android

    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:

    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:

    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 with TextView:

    Here we will use the gradient background for TextView:

    The output of the above code is:

    Gradient background with ImageView:

    Here we will use the gradient background for ImageView:

    The output of the above code is:

    Gradient background with SeekBar:

    Here we will use the gradient background for SeekBar:

    The output of the above code is:

    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.

    Источник

    How to Add a Gradient Background to an Android App

    Adding a gradient as a background color to your an Android app can add extra interest and style and provide a great user experience.

    In this post, I will walk you through the steps of how to add a gradient background to your Android app including code samples.

    To add a gradient background to your Android app, you need to do the following.

    1. Create a drawable resource with a selector root element
    2. Add an item, shape, and gradient element to the drawable resource
    3. On the gradient element, set the type of gradient to use and provide the start and end colors
    4. Set the background attribute on the layout resource of your fragment or activity to use the drawable resource

    Creating a Gradient Background in Android using a Drawable Resource

    In this section of this post, I will go through step by step of how to create a gradient background in Android using a drawable resource.

    Create a Drawable Resource with a Selector Root Element

    First, we will create a new drawable resource we will use for defining the gradient.

    Switch your project in Android Studio into Project mode and navigate into the /app/src/main/res/drawable folder. Right click on the “drawable” directory, hover over the “New” item and select the “Drawable Resource File” item.

    Then the “New Drawable Resource File” dialog will appear. Provide a file name for the drawable resource file you will use for the gradient background and set the root element to “selector”. Then press the “OK” button to create the drawable resource file.

    For drawable resources in Android, the selector element allows you to define child item elements that are selected based on a particular state. For example, a button could have different child items with different visual characteristics depending on whether the button is currently selected, focused, or pressed.

    You should end up with a drawable resource file that contains a single selector element.

    Adding an Item, Shape, and Gradient Element to the Drawable Resource

    Next, we will make some minor changes the drawable resource file we created in the previous step for the gradient background.

    Within the selector element, we will add a single item element. Each option to be selected from a selector is represented by an item element. We will only create a single item element as we do not need to change the appearance of the gradient based on a particular state.

    Within the item element, we will add a shape element. The shape element can be used to define different shapes such as rectangles, lines, ovals and rings. It allows you to customize the appearance of the shape by changing characteristics such as the corners, setting a gradient, adding padding, setting the width and height sizes, setting a solid fill color and changing the outline of the shape using the stroke element.

    Within the shape element, we will add a gradient element which we will configure in the next step to define the appearance of the gradient we will use for the background.

    See a code sample below of a drawable resource file containing the selector, item, shape and gradient elements.

    Configuring the Gradient Element in the Drawable Resource

    In this part of the tutorial, we will add attributes to the gradient element in the drawable resource we created for the gradient background to configure the appearance of the gradient.

    This will involve selecting the pattern of gradient we want to use, setting the colors of the gradient, and setting the positioning, direction, and size of the gradient.

    Setting the Gradient Pattern

    There are three gradient pattern options to choose from in Android.

    The gradient pattern is defined on the gradient element by adding the android:type attribute and setting the value to either “linear”, “radial” or “sweep”.

    The linear gradient is the default gradient.

    See a sample screenshot of a linear gradient used for a gradient background in Android below.

    Sample drawable resource code for the linear gradient pattern.

    The radial gradient allows you to define a circular center color of the gradient using the start color attribute. The size of the circle can be defined using the gradient radius attribute.

    See a sample screenshot of a radial gradient used for a gradient background in Android below.

    Sample drawable resource code for the radial gradient pattern.

    The sweep gradient offers a sweeping line gradient.

    See a sample screenshot of a sweep gradient used for a gradient background in Android below.

    Sample drawable resource code for the sweep gradient pattern.

    Setting the Gradient Colors

    There are up to three colors that can be defined on a gradient.

    • Start color which is defined using the android:startColor attribute
    • End color which is defined using the android:endColor attribute
    • Center color which is defined using the android:centerColor attribute

    These colors are set as attributes on the gradient element and the value can either be a hexidemical value representing a color e.g. “#FFFFFF” for the color white or they can be set using a color resource.

    Using a color resource is a good method to use as it allows you to define all the colors you use across your Android app in a single location inside the colors.xml resource file in the /app/src/main/res/values directory to simplify any color branding changes you want to make to your Android app in the future.

    See a sample colors resource file below containing three colors.

    See a screenshot below of a linear gradient with the start, end and center colors defined.

    This linear gradient with start, center and end colors was created using the following code.

    It is also worth mentioning there are some great free tools available on the internet that can help you find contrasting colors that are pleasant to look at to use for gradients.

    Two tools I like are UI Gradients and Web Gradients.

    Screenshot from UI Gradients Screenshot from Web Gradients

    Setting the Positioning, Direction, and Size of the Gradient

    The center position of the gradient can be changed using the android:centerX and android:centerY attributes. The value of the centerX and centerY attributes is a relative position defined as a Float value ranging from 0 to 1.0.

    The angle of the gradient can be set using the android:angle attribute using the Integer value representing the angle in degrees. This value must be a multiple of 45. A value of 0, which is the default value, represents an angle of left to right, a value of 90 represents an angle of bottom to top.

    In the case of a radial gradient pattern, the size of the circle in the gradient can be changed using the android:gradientRadius attribute which will accept a Float value.

    Setting Background Attribute to use the Drawable Resource

    Now that we have finished creating the gradient in the drawable resource file, we will need to update the layout resource file for our Activity or Fragment to the drawable resource for the background.

    In your layout resource file for your Activity or Fragment, locate the root layout whether that is a LinearLayout, RelativeLayout, ConstraintLayout, or something else, and set the android:background attribute on the layout to the drawable resource we created.

    See a code sample for setting a drawable resource as a background for a ConstraintLayout for the main activity inside the activity layout resource file.

    Bonus: A Great Tool to Automate the Creation of Gradient Backgrounds in Android

    As I was putting together this tutorial I found a free tool that can speed up this process for generating gradient backgrounds for Android apps.

    There is a free to use code generator tool available on the internet called Angry Tools that can be used to generate the code for the drawable resource containing the gradient using the user interface.

    Angry Tools – Code Generator for Gradient Drawable Resources in Android

    Источник

    Читайте также:  Изменить цвет клавиатуры андроид хуавей
    Оцените статью
    Attributes Description
    android:startColor