繁体   English   中英

我可以在 Android Canvas 的边界之外绘图吗

[英]Can I draw outside the bounds of an Android Canvas

我正在移植一个在图形环境中编写的应用程序,该应用程序允许在剪切矩形的边界之外进行绘图。 有什么办法可以在Android中做到这一点?

要在边界外绘制,您需要展开画布的clipRect。

查看Canvas类上的重载clipRect方法。

注 - 您需要指定Region操作,因为默认操作是INTERSECT。 所以像这样:

Rect newRect = canvas.getClipBounds();
newRect.inset(-5, -5)  //make the rect larger

canvas.clipRect (newRect, Region.Op.REPLACE);
//happily draw outside the bound now

试着设定

android:clipChildren="false" 

到父视图

您可以在您喜欢的地方绘制,但在剪切矩形之外不会保存任何内容。

@numan给出的答案几乎没问题,问题是用这种方法分配内存,所以我们应该这样做,而不是:

// in constructor/elsewhere
Rect newRect = new Rect();

// in onDraw
canvas.getClipBounds(newRect);
newRect.inset(0, -20);  //make the rect larger
canvas.clipRect(newRect, Region.Op.REPLACE);

这解决了问题:-)

如果你想在TextView中绘制超出范围的文本,你应该这样做:

<TextView
    ...
    android:shadowColor="#01000000"
    android:shadowDx="100" // out of right bound
    android:shadowDy="0"
    android:shadowRadius="1"
.../>

它不像@numan的回答那样使用clipRect(),因为TextView在onDraw()中剪辑它自己的rect:

if (mShadowRadius != 0) {
    clipLeft += Math.min(0, mShadowDx - mShadowRadius);
    clipRight += Math.max(0, mShadowDx + mShadowRadius);

    clipTop += Math.min(0, mShadowDy - mShadowRadius);
    clipBottom += Math.max(0, mShadowDy + mShadowRadius);
}

canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom);

最后但并非最不重要的,不要忘记在您的父ViewGroup中设置android:clipChildren="false"android:clipToPadding="false"

如果您想要的只是在视图边界之外(以编程方式)绘制,请长话短说。

parentLayout.setClipChildren(false);

或通过 xml :

 android:clipChildren="false" 

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM