Pergunta

I am trying to make a custom view for Android. I need a big ractangle that holds 7 other rectangles (equally spaced and padded from inside the main rectangle, representing days of week). With my current code, I get the following result:

enter image description here

But what I am looking for should be (the ratio is not important as long as spaces are equal):

enter image description here

Here is my code. Any help and suggestion will be appriciated!

    @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();
}
Foi útil?

Solução

When you loop through setting the small rect, you set the top as boxMain.top + space every time, and only increment the bottom. So really you are drawing 7 rectangles over the top of each other, but with increasing height each time.

Try something like the following:

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
    );

}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top