How can I cut a layout (LinearLayout or RelativeLayout) diagonally with content inside?
The mockup looks like that:
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.
You can draw the background of every ViewGroup by yourself.
There are some key points in this solution:
You need to extend the desired ViewGroup
:
public class DiagonalLayout extends LinearLayout
Override the function:
protected void dispatchDraw(Canvas canvas)
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:
What the code above does is:
Canvas
state, clip Canvas
to the polygon and fill it with colorCanvas
to original size, draw second polygonTo draw a bitmap, use drawBitmap (Bitmap bitmap, Matrix matrix, Paint paint)
method instead of filling it with red color.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With