1

I've created a custom view width grid drawing on canvas. Now my grid rows and cols count depend on actual grid width and height and also fixed cell size(16dp). So if I have grid width=160dp and height=192dp then there will be 10 cols and 12 rows. But when I have width, for example, 168 then last col will be a little bit bigger(8dp), like the last row an the picture below. enter image description here

Here is my code:

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

How can make my last cols and rows same sizes?

Gleb
  • 1,412
  • 1
  • 23
  • 55
  • I see the first vertical line is at the left edge of the view. Could it be possible that the first horizontal line being drawn is at the top of the view? This would explain the missing line at the bottom. – The Hungry Androider May 31 '16 at 19:23

1 Answers1

0

Actually, judging from your code, the last row should be bigger, not a column. 168 / 16 = 10.5, the vertical line will drawn 10 times, so the last row should be wider as it is bounded by last line (x = 144) and the boundary of canvas (x = 168) and have width = 22dp. With a desired cell size being fixed (16dp), you cannot make them the same size that way unless canvas width and height is divisible by 16.