Android shape with image

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».

    Источник

    Android shape with image

    Shape Image View

    Provides a set of custom shaped android imageview components, and a framework to define more shapes. Implements both shader and bitmap mask based image views.

    • Shader based one uses canvas draw methods and Path class,
    • Mask based one uses xfermode to draw image on bitmaps defined by android shape XML’s or resource bitmaps.

    There are many projects online implementing such components, however one goal of this project is to provide a performant/smooth scrolling image view component framework to define different shapes for imageviews.

    For use with recycling view such as ListView or GridView please use shader based implementations.

    ###Shader Based ImageView’s ####BubbleImageView

    • siTriangleHeight the height of the bubble pointer in dp
    • siArrowPosition where to point the arrow, currently left|right
    • siSquare set width and height to the minimum of the given values true|false

    ####RoundedImageView

    • siBorderColor border color
    • siBorderWidth border width in dp
    • siBorderAlpha alpha value of the border between 0.0-1.0
    • siRadius corner radius in dp
    • siSquare set width and height to the minimum of the given values true|false

    ####CircularImageView

    • siBorderColor border color
    • siBorderWidth border width in dp
    • siBorderAlpha alpha value of the border between 0.0-1.0

    ####ShapeImageView This view has the capability to process a provided SVG file (for a limited set of SVG elements), build a Path object and draw it on the shader. The library includes SVG files defining a set of basic shapes and ShapeImageView subclasses using those files. You can use whatever SVG you want to have a wonderful and creatively shaped images in your application. The included SVG files are under library/src/main/res/raw

    DiamondImageView PentagonImageView HexagonImageView
    OctogonImageView StarImageView HeartImageView
    • siBorderColor border color
    • siBorderWidth border width in dp
    • siBorderAlpha alpha value of the border between 0.0-1.0
    • siStrokeCap border stroke cap type butt|round|square
    • siStrokeJoin border stroke join type bevel|miter|round
    • siSquare set width and height to the minimum of the given values true|false
    • siShape a reference to an SVG. This is used by ShapeImageView, not the subclasses of it.

    SVG elements that are supported are: rectangle, circle, ellipse, polygon, path, group. Transformations on those elements are also supported.

    The system converts an SVG file into a Path. For each element including the parent element a new Path is created, and all the children Path’s are added to their parent path.

    ###Bitmap Mask Based ImageViews

    This view uses extra bitmaps for bitmap masks. Therefore it would be good to use them for very custom shapes, possibly not in a recycling view.

    rounded rectangle shape definition in XML:

    • siShape the bitmap mask shape, either a shape drawable or a bitmap
    • siSquare set width and height to the minimum of the given values true|false

    This method reads a shape file (either bitmap or an android shape xml), creates a bitmap object using this shape, and finally combines the bitmap of the real image to be shown and the mast bitmap using xfermode.

    See/execute the sample for a demonstration of the components.

    If you are lazy check this youtube video demonstrating scrolling in the sample app

    Источник

    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:

    Источник

    ShapeableImageView – Material components for android [Example]

    Do you want to change the shape of your ImageView in android ? . If yes then its the right place to look into it. Material Design 1.2.0 introduced ShapeableImageView that draws the image with the provided Shape in your imageview.

    By using ShapeableImageView, you can change the shape of your image to circle, diamond, etc. Also, you can set a corner radius to your imageview. You can do much more by using this ShapeableImageView with minimal code.

    before getting started, check out my other post in material design,

    To work with ShapeableImageView in your android project, you need to add dependency material design 1.2.0 or higher.

    Before starting checkout my other post on material design:

    Table of Contents

    Important attributes of ShapeableImageView

    app:shapeAppearanceOverlay — This is working as a ThemeOverlay. ShapeAppearanceOverlay applies the defined changes without affecting the active theme.

    The key to the overlay behavior is the empty parent attribute. This is what causes the overlay behavior. Lets create imageview in different shapes.

    In the above style, cornerSize only affected by the overlay. remaining properties same as active theme.

    cornerFamily — corner family to be used for all four corners

    cornerFamilyTopLeft — corner family to be used for the top left corner

    cornerFamilyTopRight — corner family to be used for the top right corner

    cornerFamilyBottomRight — corner family to be used for the bottom right corner

    cornerFamilyBottomLeft — corner family to be used for the bottom left corner

    cornerFamily is a enum type and the supported values are rounded, cut.

    cornerSize — corner size to be used for all four corners

    cornerSizeTopLeft — corner size to be used for the top left corner

    cornerSizeTopRight — corner size to be used for the top right corner

    cornerSizeBottomRight — corner size to be used for the bottom right corner

    cornerSizeBottomLeft — corner size to be used for the bottom left corner

    Imageview in circle shape

    Using XML

    as mentioned above, first we need to set the app:shapeAppearanceOverlay. In the overlay, we need to mention the corner radius size to 50% to make the imageview a circle.

    In your style.xml add,

    If you want to add stroke to circle imageview, you can add stroke attributes in your ShapeableImageView.

    Dynamically using Kotlin

    set the corner radius in dimens.xml

    Corner Radius Imageview

    Using XML

    we need to set the app:shapeAppearanceOverlay. In the overlay we need to mention the corner radius size to 10% to set the corner radius.

    In your style.xml add,

    same way, If you want to add stroke to corner radius imageview, you can add stroke attributes in your ShapeableImageView.

    Dynamically using Kotlin

    set the corner radius in dimens.xml

    Corner cut imageview

    Using XML

    For the corner cut imageview, we are going to use cornerFamily attribute.

    by default, cornerFamily will be rounded. In our case, we need it to be cut. So we are changes cornerFamily to cut.

    in style.xml :

    By changing the cornerSize, we can make different shapes like diamond, hexagon, etc.

    Dynamically using Kotlin

    setAllCorners() used to set both cornerFamily and cornerRadius.

    Selected Corner Radius / Cut imageview

    Using XML

    To set corner radius for the selected position, we need to use both cornerSize and cornerFamily for the particular position.

    For example, check the below example to set the corner radius for the right top position of the imageview.

    in style.xml :

    for the cut corner radius in style.xml :

    same way for the multiple corners, we need to add cornerRadius and cornerFamily.

    in style.xml :

    Dynamically using Kotlin

    setTopRightCorner() used to set the corner radius for the top right corner. To set multiple corners we can use setBottomLeftCorner(), setTopLeftCorner() and setBottomRightCorner() .

    Thanks for reading.

    You can download the example in github.

    Источник

    Читайте также:  Очень странные дела андроид
    Оцените статью