Cut part of XML shape

拟墨画扇 提交于 2019-12-11 07:58:21

问题


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:

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).


回答1:


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




回答2:


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:

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



来源:https://stackoverflow.com/questions/41207201/cut-part-of-xml-shape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!