以编程方式创建带有矩形切口的矩形按钮

时间:2018-10-09 20:55:03

标签: java android graphics

试图制作一个具有矩形切口的矩形ShapeDrawable-实际上需要对其进行切口,以使中间部分是“透明的”,它不能是在较大的非白色或类似的东西之上的白色矩形。

这是我到目前为止所拥有的(不过,可以看到的只是矩形的顶部“栏”,尽管它是切口的颜色,但奇怪的是黑色):

    PorterDuffColorFilter pd = new PorterDuffColorFilter(Color.BLACK, PorterDuff.Mode.SRC_OUT);
    ShapeDrawable cutout = new ShapeDrawable();
    cutout.setBounds(top.x, top.y, top.x+cellLength*matCols, top.y+cellLength*matRows);
    cutout.setColorFilter(pd);
    ShapeDrawable border = new ShapeDrawable();
    border.setBounds(Math.round(top.x-thick*cellLength), Math.round(top.y-thick*cellLength), Math.round(top.x+cellLength*(matCols+thick)), Math.round(top.y+cellLength*(matRows+thick)));
    LayerDrawable ogre = new LayerDrawable(new Drawable[]{cutout, border});
    Button test = new Button(this.getContext());
    test.setLayoutParams(new LayoutParams((int)Math.round(cellLength*(matCols + 2*thick)), (int)Math.round(cellLength*thick)));
    test.setBackground(ogre);

2 个答案:

答案 0 :(得分:0)

为什么不创建可绘制的xml:

rect.xml

<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="4dp" android:color="#000000"></stroke>
</shape>

并像这样使用它:

test.setBackgroundResource(R.drawable.rect);

答案 1 :(得分:0)

您可以在我们的可绘制对象中使用PathShape代替默认矩形。在路径上添加两个矩形,它们的路径方向相反,这样一个矩形就会被切掉。

或者您可以将边框划分为不与剪切区域重叠的顶部,底部,左侧和右侧矩形。