在矩形内绘制等间距矩形

时间:2013-12-09 01:33:19

标签: java android graphics drawrect rectangles

我正在尝试为Android制作自定义视图。我需要一个大的ractangle,它可以容纳7个其他矩形(从主矩形内部等距离填充,代表星期几)。使用我当前的代码,我得到以下结果:

enter image description here

但我要找的是(只要空格相等,这个比例就不重要了):

enter image description here

这是我的代码。任何帮助和建议都会得到满足!

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

    //Main rectangle
    Rect boxMain = new Rect();
    boxMain.set(getLeft() + 25, getTop() + 25, getRight() - 25, getBottom() - 25);

    int hMiniBox = boxMain.height() / 7; //height for each of 7 rectangles
    int space = 10; //Space between each rectangle inside the main rectangle
    int rectH = hMiniBox; //Height of each rectangle

    //Draw the main rectangle
    canvas.drawRect(boxMain, _paintProgressBoxBorder);

    //Draw 7 rectangles inside main rectangle
    for(int i = 0; i <7; i++)
    {
        Rect rect = new Rect();
        rect.set(
                boxMain.left + space,
                boxMain.top + space,
                boxMain.right - space,
                rectH
        );

        canvas.drawRect(rect, _paintProgressMiniBoxesBorder);
        rectH += hMiniBox;
    }
    invalidate();
}

1 个答案:

答案 0 :(得分:2)

当您循环设置小矩形时,每次都将顶部设置为boxMain.top + space,并且仅增加底部。所以你真的要在彼此的顶部绘制7个矩形,但每次都要增加高度。

尝试以下内容:

int smallRectTop = 0
for(int i = 0; i <7; i++) {
    Rect rect = new Rect();
    rect.set(
        boxMain.left + space,
        smallRectTop + space,
        boxMain.right - space,
        smallRectTop += hMiniBox; // Increment and set rect.bottom at the same time
    );

}