Android:在Canvas和View上绘图(不带位图)
我创建了RelativeLayout 的子级。 在它的构造函数中我调用:
public CanvasHolder(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.canvas_holder, this);
this.draw(new Canvas());
}
然后重写方法 onDraw():
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
black.setARGB(255, 0, 0, 0);
black.setAntiAlias(true);
int halfWidth = this.getWidth() / 2;
int height = this.getHeight();
canvas.drawLine(0, 0, halfWidth, height, black);
}
视图上没有出现任何线条。 另外,我尝试不调用“this.draw()”,但什么也没发生。
我发现halfWidth和height等于0。为什么?
PS即使我静态设置宽度和高度,也不会改变。 如果您不介意,请看一下这个示例应用程序:为什么没有绘制任何内容? http://androidforums.com/attachment.php?attachmentid=21715& ;stc=1&d=1315232946
I've created the child of RelativeLayout.
In its constructor I called:
public CanvasHolder(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.canvas_holder, this);
this.draw(new Canvas());
}
And then override method onDraw():
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
black.setARGB(255, 0, 0, 0);
black.setAntiAlias(true);
int halfWidth = this.getWidth() / 2;
int height = this.getHeight();
canvas.drawLine(0, 0, halfWidth, height, black);
}
No line has been appeared on the view.
Also, I tried not to call "this.draw()", but nothing happened.
I've discovered that halfWidth and height equals 0. Why?
P.S. even if I set width and height statically, nothing will change.
If you don't mind, take a look on this sample application: why nothing is drawn?
http://androidforums.com/attachment.php?attachmentid=21715&stc=1&d=1315232946
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否覆盖了
onMeasure
?这是我的 - 你可能会发现在加载视图时它会被调用几次,有时值为 0:Did you overwrite the
onMeasure
? Here's mine - you may find that this gets called a few times whilst the view is loading, sometimes with 0 values:我找到了不平凡的解决方案。我已经通过带有 1 个参数的构造函数初始化了视图。然后我在布局中插入自定义视图,并在需要时调用 invalidate() 。
I've found non-trivial solution. I've inited the view by the constructor with 1 parameter. And then I inserted the custom view in the layout and called invalidate() when I needed it.