Android create drawable from drawable

Содержание
  1. Полный список
  2. Шестиугольник
  3. Цветной шестиугольник
  4. Шестиугольник из картинки
  5. Android Shape Drawables Tutorial
  6. 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.
  7. Why should you use ShapeDrawables?
  8. Are there any disadvantages?
  9. Let’s start coding
  10. Create a simple gradient ShapeDrawable in XML
  11. GradientDrawable
  12. Class Overview
  13. Summary
  14. XML Attributes
  15. android:angle
  16. android:bottom
  17. android:centerColor
  18. android:centerX
  19. android:centerY
  20. android:color
  21. android:color
  22. android:dashGap
  23. android:dashWidth
  24. android:endColor
  25. android:gradientRadius
  26. android:height
  27. android:innerRadius
  28. android:innerRadiusRatio
  29. android:left
  30. android:right
  31. android:shape
  32. android:startColor
  33. android:thickness
  34. android:thicknessRatio
  35. android:top
  36. android:type
  37. android:useLevel
  38. android:useLevel
  39. android:visible
  40. android:width
  41. android:width
  42. Constants
  43. public static final int LINE
  44. public static final int LINEAR_GRADIENT
  45. public static final int OVAL
  46. public static final int RADIAL_GRADIENT
  47. public static final int RECTANGLE
  48. public static final int RING
  49. public static final int SWEEP_GRADIENT
  50. Public Constructors
  51. public GradientDrawable ()
  52. public GradientDrawable (GradientDrawable.Orientation orientation, int[] colors)
  53. Public Methods
  54. public void applyTheme (Resources.Theme t)
  55. public boolean canApplyTheme ()
  56. public void draw (Canvas canvas)
  57. public int getAlpha ()
  58. public int getChangingConfigurations ()
  59. public ColorFilter getColorFilter ()
  60. public Drawable.ConstantState getConstantState ()
  61. public float getGradientRadius ()
  62. public int getIntrinsicHeight ()
  63. public int getIntrinsicWidth ()
  64. public int getOpacity ()
  65. public GradientDrawable.Orientation getOrientation ()
  66. public void getOutline (Outline outline)
  67. public boolean getPadding (Rect padding)
  68. 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.

Читайте также:  Opendiag для андроид elm327

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 Attributes

android:angle

Angle 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 Methods

android:bottom

Amount 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 Methods

android:centerColor

Optional 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 Methods

android:centerX

X 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 Methods

android:centerY

Y 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 Methods

android:color

Solid 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 Methods

android:color

Color 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 Methods

android:dashGap

Gap 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 Methods

android:dashWidth

Length 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 Methods

android:endColor

End 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 Methods

android:gradientRadius

Radius 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 Methods

android:height

Height 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 Methods

android:innerRadius

Inner 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 Methods

android:innerRadiusRatio

Inner 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 Methods

android:left

Amount 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 Methods

android:right

Amount 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 Methods

android:shape

Indicates what shape to fill with a gradient.

Must be one of the following constant values.

Constant Value Description
rectangle 0 Rectangle shape, with optional rounder corners.
oval 1 Oval shape.
line 2 Line shape.
ring 3 Ring shape.

This corresponds to the global attribute resource symbol shape .

Related Methods

android:startColor

Start 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 Methods

android:thickness

Thickness 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 Methods

android:thicknessRatio

Thickness 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 Methods

android:top

Amount 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 Methods

android:type

Type of gradient. The default type is linear.

Must be one of the following constant values.

Constant Value Description
linear 0 Linear gradient.
radial 1 Radial, or circular, gradient.
sweep 2 Sweep, or angled or diamond, gradient.

This corresponds to the global attribute resource symbol type .

Related Methods

android:useLevel

Related Methods

android:useLevel

Indicates 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 Methods

android:visible

Indicates 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 Methods

android:width

Width 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 Methods

android:width

Width 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 Methods

Constants

public static final int LINE

Shape is a line

public static final int LINEAR_GRADIENT

Gradient is linear (default.)

public static final int OVAL

Shape is an ellipse

public static final int RADIAL_GRADIENT

Gradient is circular.

public static final int RECTANGLE

Shape is a rectangle, possibly with rounded corners

public static final int RING

Shape is a ring.

public static final int SWEEP_GRADIENT

Gradient is a sweep.

Public Constructors

public 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 Methods

public 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
canvas The canvas to draw into

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
  • Returns a mask of the changing configuration parameters, as defined by ActivityInfo .

public ColorFilter getColorFilter ()

Returns the current color filter, or null if none set.

Returns
  • the current color filter, or null if none set

public Drawable.ConstantState getConstantState ()

Return a Drawable.ConstantState instance that holds the shared state of this Drawable.

Returns
  • The ConstantState associated to that Drawable.

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 .

Returns

public 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
  • int The opacity class of the Drawable.

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
  • true if this drawable actually has a padding, else false. When false is returned, the padding is always set to 0.

public void inflate (Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme)

Inflate this Drawable from an XML resource optionally styled by a theme.

Источник

Читайте также:  Ремонта андроида через компьютер
Оцените статью