0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Drawableを直接描画するための基礎知識

Last updated at Posted at 2024-12-13

AndroidにおいてDrawableというと、ImageViewで表示したり、各ViewのBackground/Foregroundに指定して使うもの…ではありますが、カスタムViewなどで描画処理を実装する際は、Drawableを直接描画する必要も出てきます。

Canvasへの描画

Drawableはdrawメソッドを持っており、引数にcanvasを渡すことで、そのcanvasへの描画を行うことができます

drawable.draw(canvas)

サイズ、位置の指定

drawメソッドを使うだけだと、位置やサイズの指定ができません。
位置やサイズを指定したい場合はboundsを設定します

drawable.setBounds(left, top, right, bottom)
drawable.draw(canvas)

boundsはRectを使っても指定可能です、サイズを使い回したりする場合はこちらの方が便利ですね

val rect = Rect()
rect.set(left, top, right, bottom)
...
rect.offsetTo(left, top)
drawable.bounds = rect
drawable.draw(canvas)

9-patch

9-patch(NinePatchDrawable)の場合、このboundsはいわゆるコンテンツ領域に当たるため、9-patchで周囲にドロップシャドウなどを描いている場合、指定boundsの外側にドロップシャドウが描画されることになります。
コンテンツ領域の外側のサイズについてはgetPaddingで取得します。

(drawable as NinePatchDrawable).getPadding(rect)

Drawable自身が持っているサイズ

Drawable自身が持つサイズは intrinsicWidth / intrinsicHeight で取得することができます。
Drawableは横幅について表示の都合に応じて指定するが、高さはDrawable自身のサイズを採用するといった変形を行うことがよくあります。その場合にこれらメソッドの戻り値を利用します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?