[问题] canvas.clipPath()让绘图超出view的边界

楼主: csixty (shan)   2014-05-10 01:33:52
我想在某个 custom view 里进行绘图,而且不想让绘图超出 view
的边界,所以我在 layout file 中对此 view 的 parent ViewGroup 设定
android:clipChildren="true",这招有用,但遇到 canvas.clipPath()
指令就破功了,不知如何解决?
相关档案有3个:TestActivity.java,TestView.java,test.xml (layout)。
主要内容如下:
[TestActivity.java]
public class TestActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
}
}
[TestView.java]
public class TestView extends View {
public TestView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
// build a triangle Path object
Path pie = new Path();
pie.moveTo(-50, 50);
pie.lineTo(360, 50);
pie.lineTo(150, 400);
pie.close();
// build a paint brush
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(20);
paint.setColor(Color.RED);
// draw green triangle and red line
canvas.save();
canvas.clipPath(pie, Region.Op.REPLACE);
canvas.drawColor(Color.GREEN);
canvas.drawLine(-30, 100, 330, 100, paint);
canvas.restore();
// draw another blue line
paint.setColor(Color.BLUE);
canvas.drawLine(-30, 250, 330, 250, paint);
}
}
[test.xml]
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:clipChildren="true"
android:background="#cccccc">
<RelativeLayout
android:layout_width="200dp"
android:layout_height="350dp"
android:background="#ffffff"
android:layout_centerInParent="true"
android:clipChildren="true">
<com.example.TestView
android:id="@+id/testView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffdd"
android:layout_centerInParent="true"/>
</RelativeLayout>
</RelativeLayout>
执行画面像这样:http://ppt.cc/q7Vn
TestView 的背景是淡黄色,它的 parent 有设定 android:clipChildren="true",
这的确发挥了作用,便得蓝线在超出 TestView 的边界以外的部分不会被画出来。
但红线就不同了,由于 canvas.clipPath() 挖出一块超出 TestView 的边界的
三角形区域,使得之后的填绿色以及画红线都超出了 TestView 的边界。
想当然尔的解法是,在建立 Path 的时候要小心别超出 TestView 的边界,
或者将 Path 和 TestView 的范围进行 Region.Op.INTERSECT,
但由于种种原因,我无法这么做,不知有什么方法可以在呼叫
canvas.clipPath() 之后可以随意绘图而不超出 view 的边界?
感谢。
作者: tac0wu (在BBS中流浪)   2014-05-10 12:49:00
有趣 来研究一下你不能仰赖parent the clip来做intersect clip 你必须要自http://pastebin.com/L1aftPEp在没看android source 下的不负责猜测是 因为你内层的clip Region已经把parent给你的clip给override掉了所以你内层要自己做一下intersect clip region如何做 就看我附上code的第二段如果要贴code还是用一下置底贴code的网站
楼主: csixty (shan)   2014-05-10 18:14:00
感谢。你的code很有效。 ^__^原来,Path可以被Region来约束啊。
作者: wanilly   2014-05-11 15:39:00
小心用clipPath 因为HW加速下performance不怎么好

Links booklink

Contact Us: admin [ a t ] ucptt.com