onDraw()方法不能正常工作

时间:2015-06-11 13:57:45

标签: android canvas view ondraw

因此,iv创建了扩展视图的类。这是我的代码:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    if (!mTablesList.isEmpty()) {
        drawTables(canvas);
    }

}

 private void drawTables(Canvas canvas) {
    for (Table table : mTablesList) {

            canvas.drawRect(mWidht * table.getLeft() / 100, mHeight * table.getTop() / 100, mWidht * table.getRight() / 100, mHeight * table.getBottom() / 100, m1Paint);
            saveInfo(table, mWidht * table.getLeft() / 100, mHeight * table.getTop() / 100, mWidht * table.getRight() / 100, mHeight * table.getBottom() / 100);

    }
}

private void saveInfo(Table table, int left, int top, int right, int bottom) {

    Rect rect = new Rect();
    rect.set(left, top, right, bottom);


    table.setRect(rect);
    mTablesListTouch.add(table);
}

现在,我有2个需要绘制的对象。第一个对象总是被绘制,但第二个对象不会被绘制。当我的第二个对象坐标位于左侧且顶部==左侧和顶部时,它不会显示,当对象被绘制在对象1下方时,它会显示。有人可以给我一个解决方案吗?

private void makeTables() {

    Table table = new Table();

    table.setLeft(20);
    table.setTop(7);
    table.setRight(40);
    table.setBottom(20);
    table.setAvailable(true);
    table.setID(1);
    listOfTables.add(table);

    Table table1 = new Table();

    table1.setLeft(20);
    table1.setTop(70);
    table1.setRight(60);
    table1.setBottom(20);
    table1.setAvailable(true);
    table1.setID(2);
    listOfTables.add(table1);



    mTables.setTables(listOfTables);
}

settin mTab​​les。

好的,所以,这是setTables()方法:

 public void setTables(List<Table> tables) {
    mTablesList = tables;
    mPaint.setColor(getResources().getColor(android.R.color.black));
    invalidate();
}

之后它会调用onMeasure()和onDraw()

 @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    final int height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);


    mWidht = width;
    mHeight = height;

    setMeasuredDimension(mWidht, mHeight);

}

1 个答案:

答案 0 :(得分:0)

您没有设置正确的坐标。 table.setLeft(20)是从左边距到对象左边的值,table.setRight(30)是从对象的左边距到右边。所以,总是table.setRight&gt; table.SetLeft同样适用于顶部和底部。