2

我从 SO 的一个习惯中看到了很多transparent关于孩子背景的问题,但是似乎没有人有这个问题。ViewsViewGroup

背景:
我创建了一个自定义FrameLayout;这个容器有动态添加的视图。它的孩子应该有一个透明的背景,但容器的另一个表面必须有背景颜色。子视图可以drag'n'dropped在此容器中的任何位置。

我做什么:
我覆盖dispatchDraw(),创建一个Bitmap和一个新的Canvas,然后我用白色背景填充新的画布。
我在子视图上创建一个循环,从子维度创建一个新的,并用于Paint清除子区域。对于每个孩子,我将 Paint 和 Rect 添加到新的 Canvas。 最后,我通过传递创建的位图在 给出的主画布上使用。RectPorterDuff.Mode.DST_OUT
drawBitmapdispatchDraw()

问题:
这很好用:孩子们有一个透明的背景,其余的都是白色背景。但是,当我DragListener向孩子添加 a 时,“切割”区域没有更新(虽然dispatchDraw被正确召回):换句话说,当我拖动子视图时,它被很好地放下但透明区域仍然在同一个地方。

代码:
自定义FrameLayout

@Override
public void dispatchDraw(Canvas canvas) {
    super.dispatchDraw(canvas);
    drawCanvas(canvas);
}

private void drawCanvas(Canvas canvas) {
    // Create an off-screen bitmap and its canvas
    Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
    Canvas auxCanvas = new Canvas(bitmap);

    // Fill the canvas with the desired outside color
    auxCanvas.drawColor(Color.WHITE);

    // Create a paint for each child into parent
    for (int i = 0; i < getChildCount(); ++i) {
        // Create a transparent area for the Rect child
        View child = this.getChildAt(i);
        Paint childPaint = new Paint();
        childPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
        Rect childRect = new Rect(child.getLeft(), child.getTop(), child.getRight(), child.getBottom());
        auxCanvas.drawRect(childRect, childPaint);
    }

    // Draw the bitmap into the original canvas
    canvas.drawBitmap(bitmap, 0, 0, null);
}

DragListenerwith事件ACTION_DROP

case DragEvent.ACTION_DROP:
    x = event.getX();
    y = event.getY();

    FrameLayout frame = (FrameLayout) v;
    View view = (View) event.getLocalState();
    view.setX(x - (view.getWidth()/2));
    view.setY(y - (view.getHeight()/2));
    frame.invalidate();
    break;

截图:

关于我找到的所有问答,我尝试了很多东西,但似乎没有任何效果。
任何帮助将不胜感激。

4

1 回答 1

1

最后,我找到了线索:透明Paint的在更新后没有得到正确的 x 和 y 轴值。

我猜想getLeft(), getTop(),getRight()并且getBottom()在下降时不会改变。奇怪的是,在我的日志中,这些值似乎已更新。因此,我尝试DragEvent.ACTION_DROP使用getX()and使用更新后的值getY(),它正确地更改了透明区域的坐标。

循环中的孩子的解决方案:

Paint childPaint = new Paint();
childPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
// Use the x and y axis (plus the width and height)
Rect childRect = new Rect(
    (int) child.getX(),
    (int) child.getY(),
    (int) child.getX() + child.getWidth(),
    (int) child.getY() + child.getHeight()
);
auxCanvas.drawRect(childRect, childPaint);
于 2016-04-20T13:11:54.057 回答