Skip to content

Instantly share code, notes, and snippets.

@unrarp
Created November 6, 2013 14:27
Show Gist options
  • Save unrarp/7336890 to your computer and use it in GitHub Desktop.
Save unrarp/7336890 to your computer and use it in GitHub Desktop.
Custom Android view that divides its layout into a grid by drawing equally spaced lines both horizontally and vertically
package com.rahul.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class GridLineView extends View {
private static final int DEFAULT_PAINT_COLOR = Color.WHITE;
private static final int DEFAULT_NUMBER_OF_ROWS = 3;
private static final int DEFAULT_NUMBER_OF_COLUMNS = 3;
private boolean showGrid = false;
private final Paint paint = new Paint();
private int numRows = DEFAULT_NUMBER_OF_ROWS, numColumns = DEFAULT_NUMBER_OF_COLUMNS;
public GridLineView(Context context) {
super(context);
init();
}
public GridLineView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public GridLineView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
paint.setColor(DEFAULT_PAINT_COLOR);
}
public void setLineColor(int color) {
paint.setColor(color);
}
public void setStrokeWidth(int pixels) {
paint.setStrokeWidth(pixels);
}
public int getNumberOfRows() {
return numRows;
}
public void setNumberOfRows(int numRows) {
if (numRows > 0) {
this.numRows = numRows;
} else {
throw new RuntimeException("Cannot have a negative number of rows");
}
}
public int getNumberOfColumns() {
return numColumns;
}
public void setNumberOfColumns(int numColumns) {
if (numColumns > 0) {
this.numColumns = numColumns;
} else {
throw new RuntimeException("Cannot have a negative number of columns");
}
}
public boolean isGridShown() {
return showGrid;
}
public void toggleGrid() {
showGrid = !showGrid;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
if (showGrid) {
int width = getMeasuredWidth();
int height = getMeasuredHeight();
// Vertical lines
for (int i = 1; i < numColumns; i++) {
canvas.drawLine(width * i / numColumns, 0, width * i / numColumns, height, paint);
}
// Horizontal lines
for (int i = 1; i < numRows; i++) {
canvas.drawLine(0, height * i / numRows, width, height * i / numRows, paint);
}
}
}
}
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/darker_gray" />
<com.photoink.ui.view.GridLineView
android:id="@+id/grid_line_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment