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.
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?