自定义边框布局包含半个圆形。

3
我需要创建一个包含标题和描述的XML文档。 在标题布局中,我需要在左下和右下方添加半圆形边框,在描述布局中则需要在左上和右上方添加半圆形边框。 以下是我的设计:

enter image description here

我可以通过在矩形半径边框线上创建两个半圆来实现,但我不想使用这种方法。 我该如何用另一种方法实现呢? 请给我关键词或解决方案! 非常感谢!
1个回答

3
你可以使用 ShapeAppearanceModel 定义自定义的 CornerTreatment 来应用于组件。类似这样:
    val radius = resources.getDimension(R.dimen.default_corner_radius)
    val title_layout = findViewById<LinearLayout>(R.id.title_layout)
    
    val titleShapeModel = ShapeAppearanceModel().toBuilder()
            .setTopLeftCorner(CornerFamily.ROUNDED, radius)
            .setTopRightCorner(CornerFamily.ROUNDED, radius)
            .setBottomLeftCorner(ConcaveRoundedCornerTreatment()).setBottomLeftCornerSize(radius)
            .setBottomRightCorner(ConcaveRoundedCornerTreatment()).setBottomRightCornerSize(radius)
            .build()
    val titleBackground = MaterialShapeDrawable(titleShapeModel)
    titleBackground.setStroke(1f, ContextCompat.getColor(this, R.color.colorPrimaryDark))

    ViewCompat.setBackground(title_layout, titleBackground)

其中 ConcaveRoundedCornerTreatment 位于:

class ConcaveRoundedCornerTreatment : CornerTreatment() {

    override fun getCornerPath(
            shapePath: ShapePath,
            angle: Float,
            interpolation: Float,
            radius: Float
    ) {
        val interpolatedRadius = radius * interpolation
        shapePath.reset(0f, interpolatedRadius, ANGLE_LEFT, ANGLE_LEFT - angle)
        shapePath.addArc(
                -interpolatedRadius,
                -interpolatedRadius,
                interpolatedRadius,
                interpolatedRadius,
                ANGLE_BOTTOM,
                -angle
        )
    }

    companion object {
        const val ANGLE_LEFT = 180f
        const val ANGLE_BOTTOM = 90f
    }
}

只需对描述布局执行相同操作:

enter image description here

如果你正在使用像 CardView 这样具有内置 shapeAppearanceModel 的视图:
cardView.shapeAppearanceModel = cardView.shapeAppearanceModel.toBuilder()
        .setTopRightCorner(concaveRoundedCornerTreatment).
        .........
        .build()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接