- Полный список
- Шестиугольник
- Цветной шестиугольник
- Шестиугольник из картинки
- Android Shape Drawables Tutorial
- 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.
- Why should you use ShapeDrawables?
- Are there any disadvantages?
- Let’s start coding
- Create a simple gradient ShapeDrawable in XML
- GradientDrawable
- Class Overview
- Summary
- XML Attributes
- android:angle
- android:bottom
- android:centerColor
- android:centerX
- android:centerY
- android:color
- android:color
- android:dashGap
- android:dashWidth
- android:endColor
- android:gradientRadius
- android:height
- android:innerRadius
- android:innerRadiusRatio
- android:left
- android:right
- android:shape
- android:startColor
- android:thickness
- android:thicknessRatio
- android:top
- android:type
- android:useLevel
- android:useLevel
- android:visible
- android:width
- android:width
- Constants
- public static final int LINE
- public static final int LINEAR_GRADIENT
- public static final int OVAL
- public static final int RADIAL_GRADIENT
- public static final int RECTANGLE
- public static final int RING
- public static final int SWEEP_GRADIENT
- Public Constructors
- public GradientDrawable ()
- public GradientDrawable (GradientDrawable.Orientation orientation, int[] colors)
- Public Methods
- public void applyTheme (Resources.Theme t)
- public boolean canApplyTheme ()
- public void draw (Canvas canvas)
- public int getAlpha ()
- public int getChangingConfigurations ()
- public ColorFilter getColorFilter ()
- public Drawable.ConstantState getConstantState ()
- public float getGradientRadius ()
- public int getIntrinsicHeight ()
- public int getIntrinsicWidth ()
- public int getOpacity ()
- public GradientDrawable.Orientation getOrientation ()
- public void getOutline (Outline outline)
- public boolean getPadding (Rect padding)
- public void inflate (Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme)
Полный список
В прошлых уроках мы рассмотрели несколько системных Drawable, теперь предлагаю вам научиться создавать их самим. Drawable – это абстрактный класс, и его наследникам необходимо реализовать 4 следующих метода:
1) public abstract void draw(Canvas canvas) – это, пожалуй, самый главный метод, т.к. здесь нам дается канва и нам необходимо на ней нарисовать то, что должен отображать наш кастомный Drawable
2) public abstract int getOpacity() – насколько я понял хелп, в этом методе нам следует вернуть значение прозрачности нашего Drawable. Всего есть 4 константы:
TRANSPARENT – Drawable будет полностью прозрачным
TRANSLUCENT – Drawable будет состоять из прозрачных и непрозрачных участков
OPAQUE – Drawable будет полностью непрозрачным
Т.е. если кто-то, например, надумает из вашего Drawable сделать bitmap, то он может методом getOpacity запросить прозрачность и, если вы вернете константу OPAQUE, то это будет означать, что можно использовать конфиг RGB_565 вместо ARGB_8888, т.е. не тратить биты памяти на прозрачность. (Подробнее про конфиги, биты и память читайте в уроке 157).
3) public abstract void setAlpha (int alpha) – тут нам дают значение прозрачности и нам надо каким то образом применить это к итоговому изображению
4) public abstract void setColorFilter (ColorFilter colorFilter) – аналогичен предыдущему, только на вход идет не альфа, а ColorFilter.
Шестиугольник
Давайте создадим свой Drawable и на этом примере станет понятней как реализовать вышеописанные 4 метода. Для примера создадим Drawable, который будет выводить шестиугольник. Класс назовем HexagonDrawable и не забываем указать, что он наследник класса Drawable:
В методе draw просто выводим mPath (который будет сформирован в другом методе) на канву, используя кисть mPaint.
В методе getOpacity возвращаем TRANSLUCENT, т.к. у нас будет непрозрачный шестиугольник, а оставшееся пространство Drawable будет прозрачным. Хелп, кстати, рекомендует использовать именно TRANSLUCENT, если точно не знаете, что указать.
Методы setAlpha и setColorFilter я просто переадресую кисти mPaint. Тут все просто, т.к. кисть у меня всего одна, и она при рисовании сама учтет переданные ей эти данные.
Вообще, методы setAlpha и setColorFilter можно не реализовывать и оставить пустыми, ваш Drawable будет работать и без них. Но если вдруг кто-то (или вы сами) будет использовать ваш Drawable и захочет сделать его полупрозрачным или применить ColorFilter, то он не получит ожидаемого результата, т.к. методы не реализованы.
Кроме 4 обязательных методов пришлось еще реализовать метод onBoundsChange. Этот метод вызывается когда меняется размер Drawable. А т.к. нам нужно нарисовать 6-тиугольник размером с Drawable, мы должны знать его размер. Здесь мы получаем ширину и высоту Drawable и используем их для создания path-фигуры 6-тиугольника.
Осталось в layout повесить View, задать ему размер, например 200×200 dp и в коде задать ему наш HexagonDrawable в качестве background
Мы создали Drawable, который просто рисует 6-иугольник дефолтным черным цветом. Но это выглядит немного скучновато, поэтому давайте «добавим красок» и реализуем возможность указания любого цвета для заливки шестиугольника.
Цветной шестиугольник
Функционал уже созданного класса мы менять не будем, пусть он так и отображает черный шестиугольник. Мы создадим новый класс, который будет наследником HexagonDrawable.
Но сначала в класс HexagonDrawable все же придется добавить такой метод
Он позволит наследникам HexagonDrawable получать доступ к кисти, которая рисует шестиугольник. И, соответственно, меняя параметры кисти мы будем получать изменения рисунка.
Теперь создаем класс ColorHexagonDrawable:
Он наследует класс HexagonDrawable, который мы создали ранее, т.е. он тоже будет рисовать 6-тиугольник, но в конструкторе мы добавили возможность указания цвета. Используя добавленный в HexagonDrawable метод getPaint мы получаем кисть и задаем ей требуемый цвет.
Создаем объект ColorHexagonDrawable с указанием зеленого цвета, и давайте заодно проверим, работает ли прозрачность:
Мы указали зеленый цвет и значение прозрачности. Оба этих значения были переданы кисти, что мы и видим в итоге на экране — зеленый полупрозрачный шестиугольник.
Таким образом у нас теперь есть целых два собственных Drawable: один рисует черный шестиугольник, а второй еще и позволяет указать цвет. Сделаем третий, который возьмет Bitmap и сделает из него шестиугольник.
Шестиугольник из картинки
Создаем класс BitmapHexagonDrawable, наследуя HexagonDrawable
В конструктор передаем Bitmap, а в onBoundsChange берем размеры Drawable, создаем Bitmap этого же размера, создаем на его основе шейдер и передаем его в кисть. Про шейдеры подробнее можно почитать в Уроке 165.
Для примера я возьму вот эту картинку
Кладем ее в папку res под именем picture.png. Теперь создаем с нее Bitmap и передаем его в конструктор BitmapHexagonDrawable.
Картинка стала шестиугольной формы.
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
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:
Источник
GradientDrawable
java.lang.Object | ||
↳ | android.graphics.drawable.Drawable | |
↳ | android.graphics.drawable.GradientDrawable |
Class Overview
A Drawable with a color gradient for buttons, backgrounds, etc.
It can be defined in an XML file with the element. For more information, see the guide to Drawable Resources.
Summary
Nested Classes | |||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GradientDrawable.Orientation | Controls how the gradient is oriented relative to the drawable’s bounds |
XML Attributes | |||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
android:angle | Angle of the gradient. | ||||||||||||||||||||||||||||
android:bottom | Amount of bottom padding inside the gradient shape. | ||||||||||||||||||||||||||||
android:centerColor | Optional center color. | ||||||||||||||||||||||||||||
android:centerX | X coordinate of the origin of the gradient within the shape. | ||||||||||||||||||||||||||||
android:centerY | Y coordinate of the origin of the gradient within the shape. | ||||||||||||||||||||||||||||
android:color | Solid color for the gradient shape. | ||||||||||||||||||||||||||||
android:color | Color of the gradient shape’s stroke. | ||||||||||||||||||||||||||||
android:dashGap | Gap between dashes in the stroke. | ||||||||||||||||||||||||||||
android:dashWidth | Length of a dash in the stroke. | ||||||||||||||||||||||||||||
android:endColor | End color of the gradient. | ||||||||||||||||||||||||||||
android:gradientRadius | Radius of the gradient, used only with radial gradient. | ||||||||||||||||||||||||||||
android:height | Height of the gradient shape. | ||||||||||||||||||||||||||||
android:innerRadius | Inner radius of the ring. | ||||||||||||||||||||||||||||
android:innerRadiusRatio | Inner radius of the ring expressed as a ratio of the ring’s width. | ||||||||||||||||||||||||||||
android:left | Amount of left padding inside the gradient shape. | ||||||||||||||||||||||||||||
android:right | Amount of right padding inside the gradient shape. | ||||||||||||||||||||||||||||
android:shape | Indicates what shape to fill with a gradient. | ||||||||||||||||||||||||||||
android:startColor | Start color of the gradient. | ||||||||||||||||||||||||||||
android:thickness | Thickness of the ring. | ||||||||||||||||||||||||||||
android:thicknessRatio | Thickness of the ring expressed as a ratio of the ring’s width. | ||||||||||||||||||||||||||||
android:top | Amount of top padding inside the gradient shape. | ||||||||||||||||||||||||||||
android:type | Type of gradient. | ||||||||||||||||||||||||||||
android:useLevel | |||||||||||||||||||||||||||||
android:useLevel | Indicates whether the drawable’s level affects the way the gradient is drawn. | ||||||||||||||||||||||||||||
android:visible | Indicates whether the drawable should intially be visible. | ||||||||||||||||||||||||||||
android:width | Width of the gradient shape. | ||||||||||||||||||||||||||||
android:width | Width of the gradient shape’s stroke. |
Constants | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
int | LINE | Shape is a line | |||||||||
int | LINEAR_GRADIENT | Gradient is linear (default.) | |||||||||
int | OVAL | Shape is an ellipse | |||||||||
int | RADIAL_GRADIENT | Gradient is circular. | |||||||||
int | RECTANGLE | Shape is a rectangle, possibly with rounded corners | |||||||||
int | RING | Shape is a ring. | |||||||||
int | SWEEP_GRADIENT | Gradient is a sweep. |
Public Constructors | |||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Changes this drawable to use a single color instead of a gradient. Specify radii for each of the 4 corners. Specify radius for the corners of the gradient. Sets the center location of the gradient. Sets the radius of the gradient. Sets the type of gradient used by this drawable.. Changes the orientation of the gradient defined in this drawable. Sets the type of shape used to draw the gradient. Sets the size of the shape drawn by this drawable. Set the stroke width and color state list for the drawable. Set the stroke width and color for the drawable. Set the stroke width and color state list for the drawable. Set the stroke width and color for the drawable. Sets whether or not this drawable will honor its level property. XML Attributesandroid:angleAngle of the gradient. Must be a floating point value, such as » 1.2 «. This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol angle . Related Methodsandroid:bottomAmount of bottom padding inside the gradient shape. Must be a dimension value, which is a floating point number appended with a unit such as » 14.5sp «. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol bottom . Related Methodsandroid:centerColorOptional center color. For linear gradients, use centerX or centerY to place the center color. Must be a color value, in the form of » #rgb «, » #argb «, » #rrggbb «, or » #aarrggbb «. This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol centerColor . Related Methodsandroid:centerXX coordinate of the origin of the gradient within the shape. May be a floating point value, such as » 1.2 «. May be a fractional value, which is a floating point number appended with either % or %p, such as » 14.5% «. The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to some parent container. This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol centerX . Related Methodsandroid:centerYY coordinate of the origin of the gradient within the shape. May be a floating point value, such as » 1.2 «. May be a fractional value, which is a floating point number appended with either % or %p, such as » 14.5% «. The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to some parent container. This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol centerY . Related Methodsandroid:colorSolid color for the gradient shape. Must be a color value, in the form of » #rgb «, » #argb «, » #rrggbb «, or » #aarrggbb «. This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol color . Related Methodsandroid:colorColor of the gradient shape’s stroke. Must be a color value, in the form of » #rgb «, » #argb «, » #rrggbb «, or » #aarrggbb «. This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol color . Related Methodsandroid:dashGapGap between dashes in the stroke. Must be a dimension value, which is a floating point number appended with a unit such as » 14.5sp «. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol dashGap . Related Methodsandroid:dashWidthLength of a dash in the stroke. Must be a dimension value, which is a floating point number appended with a unit such as » 14.5sp «. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol dashWidth . Related Methodsandroid:endColorEnd color of the gradient. Must be a color value, in the form of » #rgb «, » #argb «, » #rrggbb «, or » #aarrggbb «. This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol endColor . Related Methodsandroid:gradientRadiusRadius of the gradient, used only with radial gradient. May be a floating point value, such as » 1.2 «. May be a dimension value, which is a floating point number appended with a unit such as » 14.5sp «. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). May be a fractional value, which is a floating point number appended with either % or %p, such as » 14.5% «. The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to some parent container. This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol gradientRadius . Related Methodsandroid:heightHeight of the gradient shape. Must be a dimension value, which is a floating point number appended with a unit such as » 14.5sp «. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol height . Related Methodsandroid:innerRadiusInner radius of the ring. When defined, innerRadiusRatio is ignored. Must be a dimension value, which is a floating point number appended with a unit such as » 14.5sp «. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol innerRadius . Related Methodsandroid:innerRadiusRatioInner radius of the ring expressed as a ratio of the ring’s width. For instance, if innerRadiusRatio=9, then the inner radius equals the ring’s width divided by 9. This value is ignored if innerRadius is defined. Default value is 9. Must be a floating point value, such as » 1.2 «. This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol innerRadiusRatio . Related Methodsandroid:leftAmount of left padding inside the gradient shape. Must be a dimension value, which is a floating point number appended with a unit such as » 14.5sp «. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol left . Related Methodsandroid:rightAmount of right padding inside the gradient shape. Must be a dimension value, which is a floating point number appended with a unit such as » 14.5sp «. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol right . Related Methodsandroid:shapeIndicates what shape to fill with a gradient. Must be one of the following constant values.
This corresponds to the global attribute resource symbol shape . Related Methodsandroid:startColorStart color of the gradient. Must be a color value, in the form of » #rgb «, » #argb «, » #rrggbb «, or » #aarrggbb «. This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol startColor . Related Methodsandroid:thicknessThickness of the ring. When defined, thicknessRatio is ignored. Must be a dimension value, which is a floating point number appended with a unit such as » 14.5sp «. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol thickness . Related Methodsandroid:thicknessRatioThickness of the ring expressed as a ratio of the ring’s width. For instance, if thicknessRatio=3, then the thickness equals the ring’s width divided by 3. This value is ignored if innerRadius is defined. Default value is 3. Must be a floating point value, such as » 1.2 «. This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol thicknessRatio . Related Methodsandroid:topAmount of top padding inside the gradient shape. Must be a dimension value, which is a floating point number appended with a unit such as » 14.5sp «. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol top . Related Methodsandroid:typeType of gradient. The default type is linear. Must be one of the following constant values.
This corresponds to the global attribute resource symbol type . Related Methodsandroid:useLevelRelated Methodsandroid:useLevelIndicates whether the drawable’s level affects the way the gradient is drawn. Must be a boolean value, either » true » or » false «. This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol useLevel . Related Methodsandroid:visibleIndicates whether the drawable should intially be visible. Must be a boolean value, either » true » or » false «. This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol visible . Related Methodsandroid:widthWidth of the gradient shape. Must be a dimension value, which is a floating point number appended with a unit such as » 14.5sp «. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol width . Related Methodsandroid:widthWidth of the gradient shape’s stroke. Must be a dimension value, which is a floating point number appended with a unit such as » 14.5sp «. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). This may also be a reference to a resource (in the form » @[package:]type:name «) or theme attribute (in the form » ?[package:][type:]name «) containing a value of this type. This corresponds to the global attribute resource symbol width . Related MethodsConstantspublic static final int LINEShape is a line public static final int LINEAR_GRADIENTGradient is linear (default.) public static final int OVALShape is an ellipse public static final int RADIAL_GRADIENTGradient is circular. public static final int RECTANGLEShape is a rectangle, possibly with rounded corners public static final int RINGShape is a ring. public static final int SWEEP_GRADIENTGradient is a sweep. Public Constructorspublic GradientDrawable ()public GradientDrawable (GradientDrawable.Orientation orientation, int[] colors)Create a new gradient drawable given an orientation and an array of colors for the gradient. Public Methodspublic void applyTheme (Resources.Theme t)Applies the specified theme to this Drawable and its children. public boolean canApplyTheme ()public void draw (Canvas canvas)Draw in its bounds (set via setBounds) respecting optional effects such as alpha (set via setAlpha) and color filter (set via setColorFilter). Parameters
public int getAlpha ()Gets the current alpha value for the drawable. 0 means fully transparent, 255 means fully opaque. This method is implemented by Drawable subclasses and the value returned is specific to how that class treats alpha. The default return value is 255 if the class does not override this method to return a value specific to its use of alpha. public int getChangingConfigurations ()Return a mask of the configuration parameters for which this drawable may change, requiring that it be re-created. The default implementation returns whatever was provided through setChangingConfigurations(int) or 0 by default. Subclasses may extend this to or in the changing configurations of any other drawables they hold. Returns
public ColorFilter getColorFilter ()Returns the current color filter, or null if none set. Returns
public Drawable.ConstantState getConstantState ()Return a Drawable.ConstantState instance that holds the shared state of this Drawable. Returns
public float getGradientRadius ()Returns the radius of the gradient in pixels. The radius is valid only when the gradient type is set to RADIAL_GRADIENT . Returnspublic int getIntrinsicHeight ()Return the intrinsic height of the underlying drawable object. Returns -1 if it has no intrinsic height, such as with a solid color. public int getIntrinsicWidth ()Return the intrinsic width of the underlying drawable object. Returns -1 if it has no intrinsic width, such as with a solid color. public int getOpacity ()Return the opacity/transparency of this Drawable. The returned value is one of the abstract format constants in PixelFormat : UNKNOWN , TRANSLUCENT , TRANSPARENT , or OPAQUE . An OPAQUE drawable is one that draws all all content within its bounds, completely covering anything behind the drawable. A TRANSPARENT drawable is one that draws nothing within its bounds, allowing everything behind it to show through. A TRANSLUCENT drawable is a drawable in any other state, where the drawable will draw some, but not all, of the content within its bounds and at least some content behind the drawable will be visible. If the visibility of the drawable’s contents cannot be determined, the safest/best return value is TRANSLUCENT. Generally a Drawable should be as conservative as possible with the value it returns. For example, if it contains multiple child drawables and only shows one of them at a time, if only one of the children is TRANSLUCENT and the others are OPAQUE then TRANSLUCENT should be returned. You can use the method resolveOpacity(int, int) to perform a standard reduction of two opacities to the appropriate single output. Note that the returned value does not necessarily take into account a custom alpha or color filter that has been applied by the client through the setAlpha(int) or setColorFilter(ColorFilter) methods. Some subclasses, such as BitmapDrawable , ColorDrawable , and GradientDrawable , do account for the value of setAlpha(int) , but the general behavior is dependent upon the implementation of the subclass. Returns
public GradientDrawable.Orientation getOrientation ()Returns the orientation of the gradient defined in this drawable. public void getOutline (Outline outline)Called to get the drawable to populate the Outline that defines its drawing area. This method is called by the default ViewOutlineProvider to define the outline of the View. The default behavior defines the outline to be the bounding rectangle of 0 alpha. Subclasses that wish to convey a different shape or alpha value must override this method. public boolean getPadding (Rect padding)Return in padding the insets suggested by this Drawable for placing content inside the drawable’s bounds. Positive values move toward the center of the Drawable (set Rect.inset). Returns
public void inflate (Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme)Inflate this Drawable from an XML resource optionally styled by a theme. Источник |