Skip to content Skip to sidebar Skip to footer

Cutting The Corners Off A Layout

I have a layout in android that needs to be a certain shape, i.e. this: where the corners are cut off. Is there a way of doing this programatically without setting the background

Solution 1:

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.shapes.Shape;

publicclassWeirdShapeextendsShape {
    privatestaticfinalintCOLOUR= Color.BLACK;
    privatestaticfinalfloatSTROKE_WIDTH=1.0f;
    privatestaticfinalfloatCORNER=35.0f;

    privatefinalPaintborder=newPaint();
    privatefinal Path  path;  

    publicWeirdShape() {
       path   = newPath();

        border.setColor      (COLOUR);
        border.setStyle      (Paint.Style.FILL);
        border.setStrokeWidth(STROKE_WIDTH);
        border.setAntiAlias  (true);
        border.setDither     (true);
        border.setStrokeJoin (Paint.Join.ROUND);  
        border.setStrokeCap  (Paint.Cap.ROUND);  
    }

    @OverrideprotectedvoidonResize(float width, float height) {
        super.onResize(width, height);

        floatdx= STROKE_WIDTH/2.0f;
        floatdy= STROKE_WIDTH/2.0f;
        floatx= dx;
        floaty= dy;
        floatw= width  - dx;
        floath= height - dy;

        //RectF arc = new RectF(x,h-2*CORNER,x+2*CORNER,h);

        path.reset();
        path.moveTo(x + CORNER,y);
        path.lineTo(w - CORNER,y);
        path.lineTo(w,y + CORNER);
        path.lineTo(w, h);
        path.lineTo(x + CORNER,h);
       // path.arcTo (arc,90.0f,90.0f);
        path.lineTo(dx,h - CORNER);
        path.lineTo(dx,y);//path.lineTo(dx,y + CORNER);
        path.close();
    }


    @Overridepublicvoiddraw(Canvas canvas, Paint paint) {
        // TODO Auto-generated method stub
        canvas.drawPath(path,border);
    }
}

and then use the custom Shape in a ShapeDrawable as the background Drawable:

view.setBackground(newShapeDrawable(newWeirdShape()));

Which looks something like:

Solution 2:

You can use the ShapeAppearanceModel provided by the Material Components Library:

    <LinearLayout
        android:id="@+id/layout"
        ..>

with:

valradius= resources.getDimension(R.dimen.cornerSize16)

    vallinearLayout= findViewById<LinearLayout>(R.id.layout)
    valshapeAppearanceModel= ShapeAppearanceModel()
        .toBuilder()
        .setTopRightCorner(CornerFamily.CUT, radius)
        .setBottomLeftCorner(CornerFamily.CUT, radius)
        .build()

    valshapeDrawable= MaterialShapeDrawable(shapeAppearanceModel)
    ViewCompat.setBackground(linearLayout, shapeDrawable)

enter image description here

Post a Comment for "Cutting The Corners Off A Layout"