0
0

More than 1 year has passed since last update.

【Android】斜めの線をCanvasで引く方法

Posted at

今回は斜めの線をCanvasで引く方法を記載しようと思います。

このやり方は簡単で、縦横の比率が変わっても角から角へ線を引くことができます。

LineView.kt
class LineView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : View(context, attrs, defStyleAttr) {
    var paint: Paint = Paint()
    override fun onDraw(canvas: Canvas) {
        // 線の太さ
        paint.strokeWidth = 4f
        // 線の色
        paint.color = ContextCompat.getColor(context, R.color.black)
        // 線を表示する位置
        canvas.drawLine(0f, height.toFloat(), width.toFloat(), 0f, paint)
    }
}

スクリーンショット

Screenshot_20221008_230732.png

このような感じで綺麗な斜め線が弾けてます。

※わかりやすいように枠をつけてます。
今回は左下から右上に向けて引いてます。

canvas.drawLine(0f, height.toFloat(), width.toFloat(), 0f, paint)

このように引数を変更すると左上から右下に引くことができます。

canvas.drawLine(0f, 0f, width.toFloat(), 0f, height.toFloat())

以上です。

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