Android bitmapdrawable from drawable

Bitmap Drawable Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

A Drawable that wraps a bitmap and can be tiled, stretched, or aligned.

Remarks

Portions of this page are modifications based on work created andВ shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

Create an empty drawable, not dealing with density.

Create an empty drawable, not dealing with density.

A constructor used when creating managed representations of JNI objects; called by the runtime.

Create an empty drawable, not dealing with density.

Create an empty drawable, not dealing with density.

Create an empty drawable, not dealing with density.

Create an empty drawable, not dealing with density.

Create an empty drawable, not dealing with density.

Create an empty drawable, not dealing with density.

Properties

Gets the current alpha value for the drawable.

(Inherited from Drawable) AutoMirrored

Tells if this Drawable will be automatically mirrored when its layout direction is RTL right-to-left. -or- Set whether this Drawable is automatically mirrored when its layout direction is RTL (right-to left).

(Inherited from Drawable) Bitmap

Returns the bitmap used by this drawable to render. -or- Switch to a new Bitmap object.

Return the drawable’s bounds Rect. -or- Specify a bounding rectangle for the Drawable.

(Inherited from Drawable) Callback

Return the current Callback implementation attached to this Drawable.

(Inherited from Drawable) ChangingConfigurations

Return a mask of the configuration parameters for which this drawable may change, requiring that it be re-created. -or- Set a mask of the configuration parameters for which this drawable may change, requiring that it be re-created.

(Inherited from Drawable) Class

Returns the runtime class of this Object .

(Inherited from Object) ColorFilter

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

(Inherited from Drawable) Current (Inherited from Drawable) DirtyBounds

Return the drawable’s dirty bounds Rect.

(Inherited from Drawable) Gravity

Get the gravity used to position/stretch the bitmap within its bounds. -or- Set the gravity used to position/stretch the bitmap within its bounds.

The handle to the underlying Android instance.

(Inherited from Object) HasAntiAlias

Indicates whether anti-aliasing is enabled for this drawable.

Indicates whether this drawable has at least one state spec explicitly specifying android.R.attr#state_focused .

(Inherited from Drawable) HasMipMap

Indicates whether the mipmap hint is enabled on this drawable’s bitmap.

Returns the drawable’s intrinsic height.

(Inherited from Drawable) IntrinsicWidth

Returns the drawable’s intrinsic width.

(Inherited from Drawable) IsAutoMirrored

Tells if this Drawable will be automatically mirrored when its layout direction is RTL right-to-left.

Whether this drawable requests projection.

(Inherited from Drawable) IsStateful

Indicates whether this drawable will change its appearance based on state.

(Inherited from Drawable) IsVisible (Inherited from Drawable) JniIdentityHashCode (Inherited from Object) JniPeerMembers LayoutDirection

Returns the resolved layout direction for this Drawable.

(Inherited from Drawable) Level

Retrieve the current level.

(Inherited from Drawable) MinimumHeight

Returns the minimum height suggested by this Drawable.

(Inherited from Drawable) MinimumWidth

Returns the minimum width suggested by this Drawable.

(Inherited from Drawable) Opacity

Return the opacity/transparency of this Drawable.

Return in insets the layout insets suggested by this Drawable for use with alignment operations during layout.

(Inherited from Drawable) Paint

Returns the paint used to render this drawable.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Читайте также:  Как обновить bq 6040l magic до 10 андроид

Indicates the repeat behavior of this drawable on the X axis. -or- Sets the repeat behavior of this drawable on the X axis.

Indicates the repeat behavior of this drawable on the Y axis. -or- Sets the repeat behavior of this drawable on the Y axis.

Returns a Region representing the part of the Drawable that is completely transparent.

(Inherited from Drawable)

Methods

Applies the specified theme to this Drawable and its children.

(Inherited from Drawable) CanApplyTheme() (Inherited from Drawable) ClearColorFilter()

Removes the color filter for this drawable.

(Inherited from Drawable) Clone()

Creates and returns a copy of this object.

(Inherited from Object) CopyBounds()

Return a copy of the drawable’s bounds in a new Rect.

(Inherited from Drawable) CopyBounds(Rect)

Return a copy of the drawable’s bounds in a new Rect.

(Inherited from Drawable) Dispose() (Inherited from Object) Dispose(Boolean) (Inherited from Object) Draw(Canvas)

Draw in its bounds (set via setBounds) respecting optional effects such as alpha (set via setAlpha) and color filter (set via setColorFilter).

Indicates whether some other object is «equal to» this one.

(Inherited from Object) GetConstantState()

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

Returns a hash code value for the object.

(Inherited from Object) GetHotspotBounds(Rect)

Populates outRect with the hotspot bounds.

(Inherited from Drawable) GetOutline(Outline)

Called to get the drawable to populate the Outline that defines its drawing area.

(Inherited from Drawable) GetPadding(Rect)

Return in padding the insets suggested by this Drawable for placing content inside the drawable’s bounds.

(Inherited from Drawable) GetState()

Describes the current state, as a union of primitve states, such as android.R.attr#state_focused , android.R.attr#state_selected , etc.

(Inherited from Drawable) Inflate(Resources, XmlReader, IAttributeSet)

Inflate this Drawable from an XML resource.

(Inherited from Drawable) Inflate(Resources, XmlReader, IAttributeSet, Resources+Theme)

Inflate this Drawable from an XML resource.

(Inherited from Drawable) InflateAsync(Resources, XmlReader, IAttributeSet) (Inherited from Drawable) InflateAsync(Resources, XmlReader, IAttributeSet, Resources+Theme) (Inherited from Drawable) InvalidateSelf()

Use the current Callback implementation to have this Drawable redrawn.

(Inherited from Drawable) JavaFinalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

(Inherited from Object) JumpToCurrentState()

If this Drawable does transition animations between states, ask that it immediately jump to the current state and skip any active animations.

(Inherited from Drawable) Mutate()

Make this drawable mutable.

(Inherited from Drawable) Notify()

Wakes up a single thread that is waiting on this object’s monitor.

(Inherited from Object) NotifyAll()

Wakes up all threads that are waiting on this object’s monitor.

(Inherited from Object) OnBoundsChange(Rect)

Override this in your subclass to change appearance if you vary based on the bounds.

(Inherited from Drawable) OnLayoutDirectionChanged(Int32)

Called when the drawable’s resolved layout direction changes.

(Inherited from Drawable) OnLevelChange(Int32)

Override this in your subclass to change appearance if you vary based on level.

(Inherited from Drawable) OnStateChange(Int32[])

Override this in your subclass to change appearance if you recognize the specified state.

(Inherited from Drawable) ScheduleSelf(Action, Int64) (Inherited from Drawable) ScheduleSelf(IRunnable, Int64)

Use the current Callback implementation to have this Drawable scheduled.

(Inherited from Drawable) SetAlpha(Int32)

Specify an alpha value for the drawable. 0 means fully transparent, and 255 means fully opaque.

Enables or disables anti-aliasing for this drawable.

Specify a bounding rectangle for the Drawable.

(Inherited from Drawable) SetCallback(Drawable+ICallback)

Bind a Callback object to this Drawable.

(Inherited from Drawable) SetColorFilter(Color, PorterDuff+Mode)

Specify a color and Porter-Duff mode to be the color filter for this drawable.

(Inherited from Drawable)

Читайте также:  Мультимедиа лада веста андроид какая лучше
SetColorFilter(ColorFilter)

Specify an optional color filter for the drawable.

Set to true to have the drawable dither its colors when drawn to a device with fewer than 8-bits per color component.

(Inherited from Drawable) SetFilterBitmap(Boolean)

Set to true to have the drawable filter its bitmaps with bilinear sampling when they are scaled or rotated.

(Inherited from Drawable) SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Object) SetHotspot(Single, Single)

Specifies the hotspot’s location within the drawable.

(Inherited from Drawable) SetHotspotBounds(Int32, Int32, Int32, Int32)

Sets the bounds to which the hotspot is constrained, if they should be different from the drawable bounds.

(Inherited from Drawable) SetLayoutDirection(LayoutDirection)

Set the layout direction for this drawable.

(Inherited from Drawable) SetLevel(Int32)

Specify the level for the drawable.

(Inherited from Drawable) SetMipMap(Boolean)

Enables or disables the mipmap hint for this drawable’s bitmap.

Specify a set of states for the drawable.

(Inherited from Drawable) SetTargetDensity(Canvas)

Set the density at which this drawable will be rendered.

Set the density at which this drawable will be rendered.

Set the density at which this drawable will be rendered.

Sets the repeat behavior of this drawable on both axis.

Specifies tint color for this drawable.

(Inherited from Drawable) SetTintBlendMode(BlendMode)

Specifies a tint blending mode for this drawable.

(Inherited from Drawable) SetTintList(ColorStateList)

Specifies tint color for this drawable as a color state list.

(Inherited from Drawable) SetTintMode(PorterDuff+Mode)

Specifies a tint blending mode for this drawable.

(Inherited from Drawable) SetVisible(Boolean, Boolean)

Set whether this Drawable is visible.

(Inherited from Drawable) ToArray () (Inherited from Object) ToString()

Returns a string representation of the object.

(Inherited from Object) UnregisterFromRuntime() (Inherited from Object) UnscheduleSelf(Action) (Inherited from Drawable) UnscheduleSelf(IRunnable)

Use the current Callback implementation to have this Drawable unscheduled.

(Inherited from Drawable) Wait()

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

(Inherited from Object) Wait(Int64)

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

(Inherited from Object) Wait(Int64, Int32)

Causes the current thread to wait until another thread invokes the java.lang.Object#notify() method or the java.lang.Object#notifyAll() method for this object.

(Inherited from Object)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Object)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Object)
IJavaPeerable.Finalized() (Inherited from Object)
IJavaPeerable.JniManagedPeerState (Inherited from Object)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Object)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Object)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Object)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

Полный список

— изучаем drawable теги: , ,

Продолжаем разбирать типы Drawable, которые можно описывать с помощью XML-разметки. Проектов в этом уроке создавать не будем. Я просто буду в своем проекте создавать XML-файлы в папке drawable и ставить их фоном для View. А в тексте урока приведу код и скрины. Иногда буду вешать дополнительно серый фон, чтобы был виден реальный размер View.

Чтобы программно добраться до Drawable, который вы для View повесили как фон, надо просто вызвать метод getBackground.

Bitmap

Тег позволяет получить Drawable обертку для Bitmap. У тега есть несколько атрибутов.

В атрибуте src указываем нужный нам файл-изображение.

Атрибут gravity указывает, как bitmap будет располагаться внутри Drawable. Можно использовать несколько значений, разделенных знаком | . Значения тут стандартные, и некоторые из них мы часто используем при работе с layout. Рассмотрим пример.

Значение атрибута gravity сдвигает изображение влево-вверх

Далее ставим следующие значение атрибута gravity:

fill_horizontal — растянуть по горизонтали

fill растянуть (используется по умолчанию)

Насколько я понял, значения clip_vertical и clip_horizontal идентичны значениям fill_vertical и fill_horizontal в случае когда Bitmap по размеру больше, чем предоставляемое ему пространство. Т.е. clip_vertical сожмет его по вертикали, так чтобы он влез. А clip_horizontal — по горизонтали.

Атрибут tileMode — это режим «плитки». Позволяет замостить вашим изображением все доступное пространство. По умолчанию он имеет значение disabled.

Читайте также:  Как обезопасить андроид от вирусов

Для примера я создам такой bitmap.

Четыре разных цвета, внутренние границы — сплошные, внешние — пунктиром.

Если tileMode = repeat, то Bitmap будет размножен и займет все доступное пространство

Далее меняем значение атрибута tileMode.

mirror – Bitmap также будет размножен, но при этом он будет чередоваться со своим отражением

clamp – растягивает края картинки на все свободное пространство

Прочие атрибуты тега :

antialias – сглаживание линий

dither – преобразование цветов, если текущей палитры недостаточно для отображения

filter – фильтр при сжатии или растягивании (пример результата использования есть в Уроке 158)

mipMap – использование mip-текстурирования. Про него можно почитать в википедии. Используйте этот режим, если планируете в процессе отображения уменьшать bitmap более чем в два раза.

Мы рассмотрели XML-описание, но вы всегда можете создать этот объект и программно. Java-реализация – класс BitmapDrawable.

Layer List

Мы можем описать Drawable, который будет состоять из нескольких Drawable-слоев. Для этого используется тег , а внутри него теги .

У нас 4 слоя. Три bitmap со стандартной иконкой и одна фигура. Атрибуты left, top, right, bottom позволяют указывать отступы. А в атрибуте id можно указать id этого Drawable-слоя.

Обратите внимание, что важен порядок тегов item. Каждый последующий слой рисуется поверх предыдущего. Например, на получившемся изображении видно, что прямоугольник проходит «над» верхней иконкой, но «под» нижней.

Мы можем в коде получать доступ к отдельным Drawable внутри LayerDrawable. Для этого сначала получаем LayerDrawable.

А затем вызываем метод findDrawableByLayerId(int id) и указываем id, который вы указывали в атрибуте id тега item. На выходе получим Drawable.

Также у LayerDrawable есть еще несколько интересных методов

getDrawable(int index) — возвращает Drawable по индексу, а не по id

getId(int index) — возвращает id по индексу

getNumberOfLayers() — возвращает кол-во Drawable-слоев

State List

Тег позволяет отображать Drawable в зависимости от состояния View. Возможные состояние View можно посмотреть в хелпе. Рассмотрим пример с двумя из них: checked и pressed. На экране будет ToogleButton. Эта кнопка переходит в состояние checked и обратно, если на нее нажимать. А во время нажатия, пока палец касается экрана, кнопка находится в состоянии pressed.

State List позволит нам использовать три разных Drawable для отображения кнопки в трех состояниях: обычное, checked, pressed. Для этого создадим три файла в папке drawable.

Прямоугольник темно-серого цвета. Этот Drawable будем отображать в обычном состоянии кнопки.

Прямоугольник темно-синего цвета. Этот Drawable будем отображать в нажатом состоянии кнопки.

Прямоугольник светло-синего цвета. Этот Drawable будем отображать когда кнопка находится в состоянии checked.

И еще один файл, button_selector.xml:

Этот последний Drawable является селектором. В нем мы используем теги item, в которых указываем для какого состояния какой Drawable использовать

В первом item мы указали state_pressed=true, а значит этот item будет выбран системой когда кнопка будет в состоянии pressed. И экране мы увидим Drawable из этого item, т.е. toogle_button_pressed.

В втором item мы указали state_checked=true, а значит этот item будет выбран системой когда кнопка будет в состоянии checked. И экране мы увидим toogle_button_checked.

В третьем item мы не указали никакого состояния, этот item будет выбран при обычном состоянии кнопки. И экране мы увидим toogle_button.

Учтите, что здесь важен порядок расположения item внутри selector. Т.е. система идет по ним по порядку и выбирает первый подходящий. Если вы третий item, который без явного указания состояния, поставите первым, то система всегда будет останавливаться на нем.

Состояния можно комбинировать, т.е. в одном item вы можете указать несколько разных состояний.

Ставим этот Drawable, как фон для ToogleButton:

В результате, сначала видим обычное состояние

Нажимаем и держим, т.е. состояние pressed

Отпускаем – включился checked

Еще раз нажмем-отпустим — выключится checked и будет снова обычное состояние. Для каждого состояния отображается свой Drawable.

У View, кстати, есть методы, которые позволяют программно управлять состоянием. Это, например: setPressed и setSelected.

Присоединяйтесь к нам в Telegram:

— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование

— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня

— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме

Источник

Оцените статью