Android:绘制画布和视图(无位图)

时间:2011-09-05 09:09:09

标签: android drawing android-canvas

我已经创建了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.为什么?

P.S。即使我静态设置宽度和高度,也不会有任何改变。 如果您不介意,请查看此示例应用程序:为什么没有绘制任何内容? http://androidforums.com/attachment.php?attachmentid=21715&stc=1&d=1315232946

2 个答案:

答案 0 :(得分:0)

您是否覆盖了onMeasure?这是我的 - 您可能会发现在视图加载时会调用几次,有时会显示0值:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
    int parentHeight = MeasureSpec.getSize(heightMeasureSpec);

    if (parentHeight > 0) {
        this.setMeasuredDimension(parentWidth, parentHeight);
        // ... other stuff ...
    }
}

答案 1 :(得分:0)

我发现了非平凡的解决方案。我用构造函数用1参数引入了视图。然后我在布局中插入自定义视图,并在需要时调用invalidate()。