在布局的底部创建三角形

时间:2020-01-28 07:54:48

标签: java android android-drawable material-components-android material-components

我正在开发一个Android应用程序,该应用程序在活动的顶部包含一个形状,我正在尝试实现它,但努力做到这一点。 the shape in the green color

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

1 个答案:

答案 0 :(得分:1)

您可以使用官方EdgeTreatment中包含的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);

enter image description here

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