3

I used the hexagon code in this tutorial and created a createHex class (Should I post the code?). The linked web page has used the following code to actually draw the hexagons using the math in createHex:

@Override
public void paint(Graphics g){
    for(int j = 0; int j < BOARD_HEIGHT; j++){
        for(int i = 0; i < BOARD_HEIGHT; I++){
            mCellMetrics.setCellIndex(i, j);
            if(mCells[j][i] != 0){
                mCellMetrics.computeCorners(mCornersX, mCornersY);
                g.setColor((mCells[j][i] == L_ON) ? COLOR.ORANGE):COLOR.GRAY;
                g.fillPolygon(mCornersX, mCornersY, NUM_HEX_CORNERS);
                g.setColor(COLOR.BLACK)
                g.drawPolygon(mCornersX, mCornersY, NUM_HEX_CORNERS);
            }
        }
    }
}

The problem I encountered is that Android does not have a Graphics class that contains all the required methods. I did about an hour and a half of fishing around the android documentation and the closest thing I found was the Path class but it doesn't have the methods I need. I want to use the hexagon code in the linked article at the top but I can't find the equivalent of the graphics class. If there isn't an equivalent, can someone show me how to get the results I want using the linked code?

My question: How can I port the code in the linked article to android?

EDIT:

I decided that it might be helpful to others (and potential answerers) if I included the hexagon code that calculates the sides and whatnot of a hexagon, so here is createHex.java:

   package com.rush;

/**
 * Uniform hexagonal grid cell's metrics utility class.
 */
public class HexGridCell {
    private static final int[] NEIGHBORS_DI = { 0, 1, 1, 0, -1, -1 };
    private static final int[][] NEIGHBORS_DJ = { 
            { -1, -1, 0, 1, 0, -1 }, { -1, 0, 1, 1, 1, 0 } };

    private final int[] CORNERS_DX; // array of horizontal offsets of the cell's corners
    private final int[] CORNERS_DY; // array of



vertical offsets of the cell's corners
    private final int SIDE;
private int mX = 0; // cell's left coordinate
private int mY = 0; // cell's top coordinate

private int mI = 0; // cell's horizontal grid coordinate
private int mJ = 0; // cell's vertical grid coordinate

/**
 * Cell radius (distance from center to one of the corners)
 */
public final int RADIUS;
/**
 * Cell height
 */
public final int HEIGHT;
/**
 * Cell width
 */
public final int WIDTH;

public static final int NUM_NEIGHBORS = 6;

/**
 * @param radius Cell radius (distance from the center to one of the corners)
 */
public HexGridCell(int radius) {
    RADIUS = radius;
    WIDTH = radius * 2;
    HEIGHT = (int) (((float) radius) * Math.sqrt(3));
    SIDE = radius * 3 / 2;

    int cdx[] = { RADIUS / 2, SIDE, WIDTH, SIDE, RADIUS / 2, 0 };
    CORNERS_DX = cdx;
    int cdy[] = { 0, 0, HEIGHT / 2, HEIGHT, HEIGHT, HEIGHT / 2 };
    CORNERS_DY = cdy;
}

/**
 * @return X coordinate of the cell's top left corner.
 */
public int getLeft() {
    return mX;
}

/**
 * @return Y coordinate of the cell's top left corner.
 */
public int getTop() {
    return mY;
}

/**
 * @return X coordinate of the cell's center
 */
public int getCenterX() {
    return mX + RADIUS;
}

/**
 * @return Y coordinate of the cell's center
 */
public int getCenterY() {
    return mY + HEIGHT / 2;
}

/**
 * @return Horizontal grid coordinate for the cell.
 */
public int getIndexI() {
    return mI;
}

/**
 * @return Vertical grid coordinate for the cell.
 */
public int getIndexJ() {
    return mJ;
}

/**
 * @return Horizontal grid coordinate for the given neighbor.
 */
public int getNeighborI(int neighborIdx) {
    return mI + NEIGHBORS_DI[neighborIdx];
}

/**
 * @return Vertical grid coordinate for the given neighbor.
 */
public int getNeighborJ(int neighborIdx) {
    return mJ + NEIGHBORS_DJ[mI % 2][neighborIdx];
}

/**
 * Computes X and Y coordinates for all of the cell's 6 corners, clockwise,
 * starting from the top left.
 * 
 * @param cornersX Array to fill in with X coordinates of the cell's corners
 * @param cornersX Array to fill in with Y coordinates of the cell's corners
 */
public void computeCorners(int[] cornersX, int[] cornersY) {
    for (int k = 0; k < NUM_NEIGHBORS; k++) {
        cornersX[k] = mX + CORNERS_DX[k];
        cornersY[k] = mY + CORNERS_DY[k];
    }
}

/**
 * Sets the cell's horizontal and vertical grid coordinates.
 */
public void setCellIndex(int i, int j) {
    mI = i;
    mJ = j;
    mX = i * SIDE;
    mY = HEIGHT * (2 * j + (i % 2)) / 2;
}

/**
 * Sets the cell as corresponding to some point inside it (can be used for
 * e.g. mouse picking).
 */
public void setCellByPoint(int x, int y) {
    int ci = (int)Math.floor((float)x/(float)SIDE);
    int cx = x - SIDE*ci;

    int ty = y - (ci % 2) * HEIGHT / 2;
    int cj = (int)Math.floor((float)ty/(float)HEIGHT);
    int cy = ty - HEIGHT*cj;

    if (cx > Math.abs(RADIUS / 2 - RADIUS * cy / HEIGHT)) {
        setCellIndex(ci, cj);
    } else {
        setCellIndex(ci - 1, cj + (ci % 2) - ((cy < HEIGHT / 2) ? 1 : 
0));
            }
        }
    }

For an explanation of how the code works please refer to the linked article.

Jax
  • 402
  • 7
  • 24
  • Found this question. Might be enough to get your started: [How to draw a line in android](http://stackoverflow.com/questions/3616676/how-to-draw-a-line-in-android). – PakkuDon May 13 '15 at 14:13
  • Might be helpful to you: http://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/ui/shape/PolygonFactory.java – ControlAltDel May 13 '15 at 14:21
  • @ControlAltDel I do not believe the java.awt.Polygon class is included in android.... – Jax May 13 '15 at 15:17
  • This is for a game. I am designing my first game engine for android and I want to use hexes to determine how far a player can move per turn. – Jax May 13 '15 at 15:27
  • @DJMethaneMan I think that you are right about android not having a Polygon object. Also, I think the algorithm/solution in PolygonFactory which I linked to is essentially the same as the one you'd already found. But I think you should be able to adapt either of these solutions to work in Android using Path and lineTo – ControlAltDel May 13 '15 at 15:28

1 Answers1

4

Try this:

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Path;
import android.graphics.Region;
import android.util.AttributeSet;
import android.view.View;

public class HexagonMaskView extends View {
    private Path hexagonPath;
    private Path hexagonBorderPath;
    private float radius;
    private float width, height;
    private int maskColor;

public HexagonMaskView(Context context) {
    super(context);
    init();
}

public HexagonMaskView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public HexagonMaskView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init() {
    hexagonPath = new Path();
    hexagonBorderPath = new Path();
    maskColor = 0xFF01FF77;
}

public void setRadius(float r) {
    this.radius = r;
    calculatePath();
}

public void setMaskColor(int color) {
    this.maskColor = color;
    invalidate();
}

private void calculatePath() {
    float triangleHeight = (float) (Math.sqrt(3) * radius / 2);
    float centerX = width/2;
    float centerY = height/2;
    hexagonPath.moveTo(centerX, centerY + radius);
    hexagonPath.lineTo(centerX - triangleHeight, centerY + radius/2);
    hexagonPath.lineTo(centerX - triangleHeight, centerY - radius/2);
    hexagonPath.lineTo(centerX, centerY - radius);
    hexagonPath.lineTo(centerX + triangleHeight, centerY - radius/2);
    hexagonPath.lineTo(centerX + triangleHeight, centerY + radius/2);
    hexagonPath.moveTo(centerX, centerY + radius);

    float radiusBorder = radius - 5;    
    float triangleBorderHeight = (float) (Math.sqrt(3) * radiusBorder / 2);
    hexagonBorderPath.moveTo(centerX, centerY + radiusBorder);
    hexagonBorderPath.lineTo(centerX - triangleBorderHeight, centerY + radiusBorder/2);
    hexagonBorderPath.lineTo(centerX - triangleBorderHeight, centerY - radiusBorder/2);
    hexagonBorderPath.lineTo(centerX, centerY - radiusBorder);
    hexagonBorderPath.lineTo(centerX + triangleBorderHeight, centerY - radiusBorder/2);
    hexagonBorderPath.lineTo(centerX + triangleBorderHeight, centerY + radiusBorder/2);
    hexagonBorderPath.moveTo(centerX, centerY + radiusBorder);
    invalidate();
}

@Override
public void onDraw(Canvas c){
    super.onDraw(c);
    c.clipPath(hexagonBorderPath, Region.Op.DIFFERENCE);
    c.drawColor(Color.WHITE);
    c.save();
    c.clipPath(hexagonPath, Region.Op.DIFFERENCE);
    c.drawColor(maskColor);
    c.save();
}

// getting the view size and default radius
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    width = MeasureSpec.getSize(widthMeasureSpec);
    height =  MeasureSpec.getSize(heightMeasureSpec);
    radius = height / 2 - 10;
    calculatePath();
}
}
Shishir Shetty
  • 2,021
  • 3
  • 20
  • 35
  • 1
    I'll test this out tonight (as I cannot code for Android from my iPad) when I get home. I'll get back to you sometime tomorrow. – Jax May 13 '15 at 19:49