如何在 Android 中绘制带有渐变的圆弧?

问题描述

我需要这张照片

What I need

在 Android 中作为自定义视图(或其他东西)绘制。另外梯度不应该是静态的,它应该根据输入旋转(想象一下温度从 -10 到 +40,它应该是从全蓝到全红,中间状态)。

我发现我需要两个位图:一个渐变矩形和一个遮罩弧。然后我可以旋转渐变矩形,就是这样。关键是我不能在矩形上方(或下方)放置蒙版

我试图重现 this 答案,但没有成功。我只能用渐变来绘制弧线,但显然这还不够。我也知道下面的代码是一团糟,但它应该是一个概念证明。

class GradientArc(context: Context,attrs: AttributeSet) : View(context,attrs) {

    private val shader1: Shader = LinearGradient(375f,0f,425f,Color.rgb(59,242,174),Color.rgb(101,172,242),Shader.TileMode.CLAMP)

    private val paint: Paint = Paint()

    val imagePaint = Paint().apply { setXfermode(PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val conf: Bitmap.Config = Bitmap.Config.ARGB_8888
        val mImage: Bitmap = Bitmap.createBitmap(width,height,conf)
        val imageCanvas = Canvas(mImage)

        paint.setstrokeWidth(70f)
        paint.setStyle(Paint.Style.stroke)
        paint.setstrokeCap(Paint.Cap.ROUND)
        paint.setAntiAlias(true)
        paint.setShader(shader1)

        val radius = 400
        val oval = RectF()
        val center_x = 500f
        val center_y = 500f

        oval[center_x - radius,center_y - radius,center_x + radius] = center_y + radius
        imageCanvas.drawArc(oval,135f,270f,false,paint)

        canvas.save()
        canvas.drawBitmap(mImage,imagePaint)
        canvas.restore()
    }
}

我想没有人会编写所有这些代码解决我的问题,但是您能否至少给我一些示例?示例最好包含渐变、蒙版和手动绘制一些图形。

我找到了 this文章,但我无法将其映射到我的案例中,因为作者没有使用自定义图并且并非所有代码示例都有效。

解决方法

我建议创建一个位图(或任何图像资源),拱门(即图表中的彩色区域)是透明的。然后将此位图放在一个方形框的顶部,其中渐变应用于方形框本身。这可能是一种更简单的方法。