简体   繁体   English

Android:在画布上绘制视图

[英]Android: Draw a view on canvas

I have a view inflated, I can draw it on canvas, but can't seem to position it properly. 我有一个充气的视图,我可以在画布上绘制它,但似乎无法正确定位它。

LayoutInflater li = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.fix_this_recommendation, null);
v.measure(MeasureSpec.getSize(v.getMeasuredWidth()), MeasureSpec.getSize(v.getMeasuredHeight()));
v.layout(400, 400, 400, 400);
v.draw(canvas);

But the view is always at the top left corner. 但视图始终位于左上角。 Anyone know why? 谁知道为什么?

Solution is to translate canvas: 解决方法是翻译画布:

canvas.save();
canvas.translate(left, top);            
view.draw(canvas);
canvas.restore();

Each View draws its contents within its own coordinate system, with (0, 0) at the top-left. 每个View在其自己的坐标系中绘制其内容,左上角为(0,0)。 If you want it to appear elsewhere, you can set a new transformation matrix on your Canvas. 如果您希望它出现在其他位置,您可以在Canvas上设置新的变换矩阵

因为Canvas使用的坐标系从左上角开始而不是定义您的自定义视图并覆盖onDraw()方法,并在其中定位视图,如您所愿

use drawChild(canvas,child,getDrawingTime()); 使用drawChild(canvas,child,getDrawingTime()); instead of child.draw(canvas) 而不是child.draw(画布)

drawChild will calc child's top and left margin drawChild将计算孩子的左上边距和左边距

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

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