2013-12-09 326 views
2

我正在嘗試爲Android創建自定義視圖。我需要一個可以容納另外7個矩形的大矩形(距主矩形內部等間距和填充,代表星期幾)。隨着我當前的代碼,我得到以下結果:在矩形內繪製等距矩形

enter image description here

但是我期待的應該是(比例並不重要,只要空間是相同的):

enter image description here

這是我的代碼。任何幫助和建議將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(); 
} 
+0

你不動的長方形的頂部邊角下來。你只是使每個連續的矩形更高。 – mbeckish

回答

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

} 
+0

你能告訴我,我應該改變什麼?我嘗試了一些編輯,但我只得到weiered的結果。 –

+0

好的將編輯我的答案 –