是否可以只使用xml代码在Android上绘制这个形状?

hrirmatl  于 2023-02-02  发布在  Android
关注(0)|答案(1)|浏览(116)

它不是半圆,它是弧形。

f2uvfpb9

f2uvfpb91#

直接在XML中设计一个弧并不是那么简单,我可能会使用如下的自定义视图来完成:

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.RectF

import android.graphics.drawable.ShapeDrawable

class ArcShape(
  private val color: Int,
  private val startAngle: Float,
  private val sweepAngle: Float
) : ShapeDrawable() {
  private val rectF: RectF = RectF()
  private val shapePaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)

  init {
    shapePaint.color = color
    shapePaint.style = Paint.Style.STROKE
    shapePaint.strokeWidth = 5f
  }

  override fun draw(
    canvas: Canvas
  ) {
    canvas.drawArc(rectF, startAngle, sweepAngle, false, shapePaint)
  }

  override fun onBoundsChange(bounds: Rect) {
    super.onBoundsChange(bounds)
    rectF.set(bounds)
  }
}

画布更灵活,可以让你设计任何你想要的!你也可以用Jetpack作曲!

相关问题