2016-05-31 1 views
1

キャンバス上にカスタムビューの幅グリッド図面を作成しました。現在、グリッドの行数と列数は、実際のグリッドの幅と高さに加え、固定セルサイズ(16dp)にも依存します。 グリッド幅= 160dp、高さ= 192dpの場合、10列と12行があります。しかし、幅があると、たとえば168の場合、最後の行のように最後の列が少し大きくなります(8dp)。ここで enter image description hereカスタムビューで最後の列と行を同じサイズにする方法

私のコードです:

public class MyGrid extends View 
{ 
    private static final int CELL_SIZE=16; 
    private int mHeight; 
    private int mWidth; 

    public MyGrid(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     setFocusable(true); 
    } 

    // getting sizes in onLayout becouse there is no sizes in constractor 
    @Override 
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 
     super.onLayout(changed, left, top, right, bottom); 
     int mWidth=getWidth()/CELL_SIZE; 
     int mHeight=getHeight()/CELL_SIZE; 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     Paint background = new Paint(); 
     background.setColor(getResources().getColor(R.color.background_color)); 
     canvas.drawRect(0, 0, getWidth(), getHeight(), background); 

     drawBorders(canvas); 
    } 

    private void drawBorders(Canvas canvas) 
    { 
     Paint line=new Paint(); 
     line.setColor(getResources().getColor(R.color.line_color)); 
     line.setStyle(Paint.Style.STROKE); 
     line.setStrokeWidth(1); 
     // verical 
     for(int i=0; i<mWidth; i++) 
      canvas.drawLine(i*CELL_SIZE, 0, i*CELL_SIZE, getHeight(), line); 
     // horizontal 
     for(int i=0; i<mHeight; i++) 
      canvas.drawLine(0, i*CELL_SIZE, getWidth(), i*CELL_SIZE, line); 
    } 
} 

私の最後のcolsと行と同じサイズを作ることができますどのように?

+0

最初の垂直線がビューの左端に表示されます。描画される最初の水平線がビューの最上部にある可能性がありますか?これは、底に欠けている線を説明するでしょう。 –

答えて

0

実際には、コードから判断すると、最後の行は列ではなく、より大きくなければなりません。 168/16 = 10.5の場合、縦線は10回描画されるので、最後の行は最後の行(x = 144)とキャンバスの境界(x = 168)と境界があり、幅= 22dpに制限されているため幅が広いはずです。キャンバスの幅と高さが16で割り切れる場合を除き、希望のセルサイズを固定して(16dp)、同じサイズにすることはできません。