0

我正在尝试在位于滚动视图内的线性布局内绘制多个矩形。这是我的矩形视图代码:

private class RectView extends View{

    int leftX, rightX, topY, bottomY;
    boolean isAppt;
    private Paint rectPaint;
    private Rect rectangle;

    public RectView(Context context, int _leftX, int _rightX, int _topY, int _bottomY, boolean _isAppt){
        super(context);
        leftX = _leftX;
        rightX = _rightX;
        topY = _topY;
        bottomY = _bottomY;
        isAppt = _isAppt;
        init();
    }

    private void init(){

            rectPaint = new Paint();

        if(isAppt){
            rectPaint.setARGB(255, 0, 0, 255);
            rectPaint.setColor(Color.BLUE);
        }
        else{
            rectPaint.setARGB(255, 0, 0, 0);
            rectPaint.setColor(Color.WHITE);
        }
        rectPaint.setStrokeWidth(2);
        rectPaint.setStyle(Style.STROKE);
        rectangle = new Rect(leftX, topY, rightX, bottomY);

    }

    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);

        canvas.drawRect(rectangle, rectPaint);
    }

}

这就是我目前尝试显示矩形的方式:

RectView rv = new RectView(context, 0, 100, 0, 100, true);
firstDemarc.addView(rv);
firstDemarc.postInvalidate();

firstDemarc 是我的滚动视图中的线性布局。目前我没有看到任何矩形。未调用 onDraw 函数。如何正确显示滚动视图内的矩形?

4

1 回答 1

0

你需要给视图一些布局参数:

int width = right - left;
int height = bottom - top;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
params.leftMargin = left;
params.topMargin = top;
setLayoutParams(params);

绘制矩形时,需要从 0,0 开始绘制,直到矩形的宽度/高度。线性布局将根据边距/布局参数处理定位。

于 2013-11-12T01:52:54.797 回答