填充画布外面的矩形

时间:2011-02-14 23:09:47

标签: android canvas

我想填充画布上矩形外的区域。我用

 canvas.drawRect(pTopLeft.x, pTopLeft.y, pBotRight.x, pBotRight.y, paint);

绘制矩形,但无法弄清楚如何填充矩形/剪辑。

由于 杰夫

4 个答案:

答案 0 :(得分:17)

感谢ted和trojanfoe - 我提出的最好的解决方案是

    Point pTopLeft = new Point();
    Point pBotRight = new Point();

    //TODO:set x,y for points

    Rect rHole = new Rect(pTopLeft.x, pTopLeft.y, pBotRight.x, pBotRight.y);
    //assume current clip is full canvas
    //put a hole in the current clip
    canvas.clipRect(rHole,  Region.Op.DIFFERENCE);
    //fill with semi-transparent red
    canvas.drawARGB(50, 255, 0, 0);
    //restore full canvas clip for any subsequent operations
    canvas.clipRect(new Rect(0, 0, canvas.getWidth(), canvas.getHeight())
                    , Region.Op.REPLACE);

答案 1 :(得分:6)

你不会在剪辑之外填写;这就是夹子有防止的东西!如果要填充rect之外的空间和绘图层边界内部,请构造四个辅助rects:

Rect above = new Rect(0, 0, canvas.getWidth(), pTopLeft.y);
Rect left = new Rect(0, pTopLeft.y, pTopLeft.x, pBotRight.y);
Rect right = new Rect(pBotRight.x, pTopLeft.y, canvas.getWidth(), pBotRight.y);
Rect bottom = new Rect(0, pBotRight.y, canvas.getWidth(), canvas.getHeight());

然后填写这些。

答案 2 :(得分:1)

ICS及以上......

canvas.clipRect(rHole,  Region.Op.DIFFERENCE);
  

XOR,差异和反向差异剪辑模式   如果启用了硬件加速,ICS会忽略它。

     

只需在视图中禁用2D硬件加速:

     

myView.setLayerType(View.LAYER_TYPE_SOFTWARE,null);

参考Android: Howto use clipRect in API15

答案 3 :(得分:0)

你不能在Canvas之外画画;该区域属于父View。您是否能够继承父View并在该类中进行绘图?

如果您想在Canvas剪辑之外绘制,那么您必须invalidate()您感兴趣的区域。