Cut part of XML shape

4.1k Views Asked by At

I have a rectangle shape view in XML:

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle"> 

        <solid android:color="@color/lightblue"/> 
    </shape>

What I want is cut it in half, so result will looks like: enter image description here

Is it possible? And if yes, how do I achieve it?

Note:

1) Adding rotated white rectangle isn't solution. I need to keep cutted area of the blue shape transparent (there are more View layers under it).

2) Bottom left corner of rect is a bit rounded (I forgot to draw it in image above).

2

There are 2 best solutions below

0
On BEST ANSWER

use a ShapeDrawable like this:

Drawable d = new ShapeDrawable(new S(Color.BLUE, 32));

where class S is a custom Shape:

class S extends Shape {
    final int color;
    final float radius;
    Path path = new Path();

    public S(int color, float radius) {
        this.color = color;
        this.radius = radius;
    }

    @Override
    protected void onResize(float width, float height) {
        path.reset();
        path.moveTo(0, 0);
        path.lineTo(width, height);
        path.lineTo(radius, height);
        RectF oval = new RectF(0, height - 2 * radius, 2 * radius, height);
        path.arcTo(oval, 90, 90);
        path.close();
    }

    @Override
    public void draw(Canvas canvas, Paint paint) {
        paint.setColor(color);
        canvas.drawPath(path, paint);
    }
}

now you can use Drawable d in any call to View#setBackground(), TextView#setCompoundDrawables() etc

5
On

Play around bit ,As of API 21 you can use vector drawables

Here is what i did, change numbers as you need . created a drawable my_custom_shape.xml as resource file

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:height="100dp"
    android:width="100dp"
    android:viewportHeight="100"
    android:viewportWidth="45" >
    <group
        android:name="triableGroup">
        <path
            android:name="triangle"
            android:fillColor="#000"
            android:pathData="m 0,0 l 50,100 -50,0 z" />
    </group>
</vector>

out put:

enter image description here

and in your View set this as backround android:background="@drawable/my_custom_shape"

Note : forgot to try use px instead of dp and see will help to keep the same size for every device , try and see