如何在 Android 中绘制一个给定大小的矩形,并将其自身定位在要添加到的视图中?
我了解如何绘制形状,我正在扩展 View
类,并重写 onDraw
,在其中创建一个新的 ShapeDrawbale
(矩形) ,然后将其绘制到画布上:
Rect rect = new Rect(x, y, x + width, y + height);
shapeDrawable.setBounds(rect);
shapeDrawable.getPaint().set(paint);
shapeDrawable.draw(canvas);
然后我想将其添加到我的“活动”布局 xml 中定义的视图中。 我通过获取视图句柄并调用:
innerLinear.addView(rectView); // where rectView is my custom class that extends View
我的问题是,在创建矩形时,您必须提供 X
和 Y
坐标。
那么 - 如何在 innerLayout
中正确定位矩形?
我是否使用 innerLayout
的边界来创建矩形?如果是这样,当我调用 innerLayout.getLeft()
或 innerLayout.getTop()
等时。总是返回 0 (我假设布局尚未完全完成),那么我该怎么做呢?
还有别的办法吗? 我觉得我在这里缺少一些非常基本的东西。
任何帮助将不胜感激,
谢谢
I understand how to draw I shape, I am extending the View
class, and overriding the onDraw
, where I create a new ShapeDrawbale
(Rectangle), which I then draw to the canvas:
Rect rect = new Rect(x, y, x + width, y + height);
shapeDrawable.setBounds(rect);
shapeDrawable.getPaint().set(paint);
shapeDrawable.draw(canvas);
I then want to add this to a view defined in my Activities layout xml.
I do this by getting a handle on the view and calling:
innerLinear.addView(rectView); // where rectView is my custom class that extends View
My problem is that when creating the Rectangle, you have to provide X
and Y
coordinates.
So - how do I get the rectanlge positioned correctly within the innerLayout
?
Do I have use the bounds of innerLayout
to create the rectangle? If so, when I call innerLayout.getLeft()
, or innerLayout.getTop()
etc.. 0 is always returned (I presume layout has not yet fully completed), so how do I do this?
Is there another way?
I feel like I'm missing something pretty basic here.
Any help would be greatly appreciated,
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
onDraw
方法中,您可以使用以下 api:对于 x 和 y,相对于父视图的参考点是 0,0。
当您在
CustomView
中调用上述 api 时,您将获得父视图的正确尺寸,在您的情况下为innerLayout
。现在,如果我必须覆盖所有区域,我将编写如下内容:这将完全填充您的
CustomView
。你的0, 0如何映射到实际的屏幕坐标,你不用担心。正如我提到的,你的视图的参考点是 0,0。 Android 会计算实际的屏幕坐标。如需进一步参考:
自定义组件
Android 如何绘制
In the
onDraw
method you can use following apis:For x and y, the reference point is 0,0 with respect to parent view.
When you call above apis in your
CustomView
you will get the right dimensions of the parent view which in your case isinnerLayout
. Now if I have to cover all the area I ll write something like:This will fill your
CustomView
completely. How your 0, 0 is mapped to the actual screen coordinates, you dont worry about it. As I mentioned, your view's reference point is 0,0. And Android will calculate the actual screen coordinates.For further ref:
Custom Components
How Android draws