Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android layout diagonal cut

How can I cut a layout (LinearLayout or RelativeLayout) diagonally with content inside?

The mockup looks like that:

enter image description here

I tried using diagonal layout libraries like https://github.com/florent37/DiagonalLayout but I cant seem to get this cut on the right of the image and on the left of the second layout with the library or with a custom View.

Any help would be appreciated.

like image 453
user754730 Avatar asked Dec 23 '22 23:12

user754730


1 Answers

You can draw the background of every ViewGroup by yourself.

There are some key points in this solution:

  1. You need to extend the desired ViewGroup:

    public class DiagonalLayout extends LinearLayout
    
  2. Override the function:

    protected void dispatchDraw(Canvas canvas)

  3. Fill the method above. Here is the sample code:

    @Override
    protected void dispatchDraw(Canvas canvas) {
        int height = canvas.getHeight();
        int width = canvas.getWidth();
        Path path = new Path();
        path.moveTo(0, 0);
        path.lineTo(width / 3 + width / 10, 0);
        path.lineTo(width / 3 - width / 10, height);
        path.lineTo(0, height);
        path.close();
        canvas.save();
        canvas.clipPath(path, Region.Op.INTERSECT);
        canvas.drawColor(ContextCompat.getColor(getContext(), android.R.color.holo_red_dark));
        canvas.restore();
        path = new Path();
        path.moveTo(width / 3 + width / 10 + width / 10, 0);
        path.lineTo(width, 0);
        path.lineTo(width, height);
        path.lineTo(width / 3, height);
        path.close();
        canvas.save();
        canvas.clipPath(path, Region.Op.INTERSECT);
        Paint paint = new Paint();
        paint.setStrokeWidth(8);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(ContextCompat.getColor(getContext(), android.R.color.black));
        canvas.drawPath(path, paint);
        canvas.restore();
        super.dispatchDraw(canvas);
    }
    

The effect of the code above is:

enter image description here

What the code above does is:

  1. Draw the polygon on the left.
  2. Save Canvas state, clip Canvas to the polygon and fill it with color
  3. Restore Canvas to original size, draw second polygon

To draw a bitmap, use drawBitmap (Bitmap bitmap, Matrix matrix, Paint paint) method instead of filling it with red color.

like image 138
R. Zagórski Avatar answered Dec 27 '22 01:12

R. Zagórski