我从SOtransparent
上的Views
一个习俗中看到了许多有关儿童背景的问题ViewGroup
,但是似乎没有人遇到这个问题。
背景:
我创建了一个自定义FrameLayout
;此容器具有动态添加的视图。它的子项应具有透明背景,但容器的另一表面必须具有背景色。子视图可以位于drag'n'dropped
此容器中的任何位置。
我的工作:
覆盖dispatchDraw()
,创建Bitmap
和一个新对象Canvas
,然后用白色背景填充新的画布。
我在子级Views上循环Paint
,Rect
从子级的尺寸创建一个new ,并用于PorterDuff.Mode.DST_OUT
清除子级的区域。对于每个孩子,我将“ Paint and Rect”添加到新的“画布”中。
最后,通过传递创建的位图,在drawBitmap
给出的主Canvas上使用dispatchDraw()
。
问题:
效果很好:孩子们的背景是透明的,其余的都是白色背景。但是,当我DragListener
向子级添加a时,“ cutting”区域不会更新(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);
}
该DragListener
用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;
屏幕截图:
关于找到的所有Q&A,我尝试了很多事情,但似乎没有任何效果。
任何帮助将不胜感激。
最终,我找到了线索:更新后,透明物体Paint
无法获得正确的x和y轴值。
我猜getLeft()
,getTop()
,getRight()
并getBottom()
在跌落不会改变。奇怪的是,在我的日志中,这些值似乎已更新。所以不是,我在更新后的值试图DragEvent.ACTION_DROP
通过使用getX()
和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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句