Android: 给视图添加四方贝塞尔圆角

Android: Add quad bezier rounded corners to View

我想要一个 ImageView 包含一个带有圆形曲线但不是圆形的图像(当然这样更容易)..

X 标记区域应为黑色,其余区域应为蓝色。它应该看起来(有点)像 this

我尝试了什么: 在一些 tools 的帮助下,我花了几个小时与 Path.quadToPath.cubicTo 战斗,但我还没有取得任何成功。老实说,我只是不太了解它的用法。

我的代码目前的样子:

override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val paint = Paint()
        paint.color = Color.BLACK
        paint.strokeWidth = 1f
        paint.strokeCap = Paint.Cap.ROUND
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)

        paint.style = Paint.Style.FILL

        val fHeight = canvas.height.toFloat()
        val startEndHeight = canvas.height / 1.18f
        val fWidth = canvas.width.toFloat()
        val halfWidth = (fWidth / 2)

        val path = Path()
        //X = Left side, Y = close to bottom
        val ptStart = PointF(0f, startEndHeight)
        //X = Middle, Y = Bottom
        val ptMiddle = PointF(halfWidth, fHeight + 95)
        // X = Right Side, Y = close to bottom
        val ptEnd = PointF(fWidth, startEndHeight)

        path.moveTo(ptStart.x, ptStart.y)
        path.quadTo(ptMiddle.x, ptMiddle.y, ptEnd.x, ptEnd.y)

        path.close()

        canvas.drawPath(path, paint)
    }

不会那么难吧? 是否可以为红色标记区域着色并保持其他一切不变?

已修复!这是我的最终解决方案,它将四边形贝塞尔曲线应用于 ImageView。我必须在路径中添加 2 行才能获得我想要的结果。

class HeaderImageView : AppCompatImageView {
    constructor(context: Context?) : super(context) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    lateinit var paint: Paint

    private fun init() {
        paint = Paint()
        paint.color = Color.WHITE
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)
        paint.style = Paint.Style.FILL
    }

    @SuppressLint("CanvasSize")
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val fHeight = canvas.height.toFloat()
        val startEndHeight = canvas.height / 1.18f
        val fWidth = canvas.width.toFloat()
        val halfWidth = (fWidth / 2)

        val path = Path()
        //X = Left side, Y = close to bottom
        val ptStart = PointF(0f, startEndHeight)
        //X = Middle, Y = Bottom
        val ptMiddle = PointF(halfWidth, fHeight + 95)
        // X = Right Side, Y = close to bottom
        val ptEnd = PointF(fWidth, startEndHeight)

        path.moveTo(ptStart.x, ptStart.y)
        path.quadTo(ptMiddle.x, ptMiddle.y, ptEnd.x, ptEnd.y)
        path.lineTo(fWidth, fHeight)
        path.lineTo(0f, fHeight)

        path.close()

        canvas.drawPath(path, paint)
    }
}