在布局底部创建一个三角形

Creating a triangle shape at the bottom of layout

我正在开发一个 android 应用程序,该应用程序在 activity 的顶部包含一个形状,我正在尝试实现它但很难做到。

我尝试创建一个可绘制文件来创建一个三角形并设置底角半径以匹配上面的形状但不起作用。任何人都可以帮助我。

您可以使用 EdgeTreatment included in the official Material Components Library.

只需将 EdgeTreatment 扩展为:

public class MyTriangleEdge extends EdgeTreatment {

  private final float size;
  private final boolean inside;

  public MyTriangleEdge(float size, boolean inside) {
    this.size = size;
    this.inside = inside;
  }

  @Override
  public void getEdgePath(
      float length, float center, float interpolation, @NonNull ShapePath shapePath) {
    shapePath.lineTo(0, 0);
    shapePath.lineTo(center, inside ? size  : -size );
    shapePath.lineTo(length, 0);
  }

然后应用它:

MyTriangleEdge edgeTreatment = new MyTriangleEdge(height,false);

LinearLayout linearLayout= findViewById(R.id.xxxx);
ShapeAppearanceModel shapeAppearanceModel = new ShapeAppearanceModel()
    .toBuilder()
    .setBottomEdge(edgeTreatment)
    .build();

MaterialShapeDrawable shapeDrawable = new MaterialShapeDrawable(shapeAppearanceModel);

ViewCompat.setBackground(linearLayout,shapeDrawable);

同样对于边缘处理,父视图必须通过在 xml 中设置 android:clipChildren="false" 来禁用子视图的剪裁。