android - 自定义边框布局包含半个圆

标签 android xml android-shapedrawable

我需要创建带有两个布局标题和描述的 xml。 在标题布局中,我需要添加边框,在左下角和右下角各有一半的圆圈,在描述布局中,边框在左上角和右上角各有一半的圆圈。 这是我的设计

enter image description here

我可以通过在矩形半径边界线上创建两个半圆来做到这一点,但我不想使用它。 我如何使用其他解决方案来做到这一点? 请给我关键的工作或解决方案! 非常感谢!

最佳答案

您可以使用 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 这样的 View ,它有一个内置的 shapeAppearanceModel:

cardView.shapeAppearanceModel = cardView.shapeAppearanceModel.toBuilder()
        .setTopRightCorner(concaveRoundedCornerTreatment).
        .........
        .build()

关于android - 自定义边框布局包含半个圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62906494/

相关文章:

java - 用于编辑 TextView 大小、样式的按钮

android - 使用服务获取 CallLog 上的最后一次通话

java - Eclipselink:persistence.xml 连接到 derby glassfish 本地主机数据库(创建并填充数据库)

android - 线条形状未出现在 Android API 21 中

android - 如何制作带有包含字母的圆圈的 CardView

android - 在小米设备上复制粘贴崩溃

android - 应用程序兼容性错误。我已经更改了谷歌地图的 API 21。但还是有一些错误

c# - 使用 REST API 返回 XML 文档

xml - 通过 apache 检查 Perl 使用了哪些核心可加载模块?

Android - 如何创建带有圆角和平铺图像背景的 View ?