I am having trouble tiling a Bitmap
. I want to have the Bitmap
drawn to coordinates defined in a 2D Array
.
I would like to be able to draw let's say "grass" to certain coordinates, and "water,etc.." to other coordinates.
I have spent days trying to figure this out, and would very greatly appreciate any insight. I can only get the Canvas
to draw 1 "grass" Bitmap
, So I feel I have an error in my for loop. I have looked here and here, amongst many others, and do not want every tile to be the same. Here is my code:
MapLoader.java
public class MapLoader extends SurfaceView implements SurfaceHolder.Callback,
Runnable {
SurfaceHolder holder;
Thread thread;
Bitmap grass = BitmapFactory.decodeResource(getResources(),
R.drawable.grass);
boolean running = false;
int[][] grassCoords = new int[][] { { 0, 16, 32, 48, 64 },
{ 0, 16, 32, 48, 64 }, { 0, 16, 32, 48, 64 },
{ 0, 16, 32, 48, 64 }, { 0, 16, 32, 48, 64 } };
public MapLoader(Context context) {
super(context);
holder = getHolder();
holder.addCallback(this);
}
public MapLoader(Context context, AttributeSet attrs) {
super(context, attrs);
holder = getHolder();
holder.addCallback(this);
}
public MapLoader(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
holder = getHolder();
holder.addCallback(this);
}
public void pause() {
running = false;
while (running) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
thread = null;
}
public void resume() {
running = true;
thread = new Thread(this);
thread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
running = true;
thread = new Thread(this);
thread.start();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Canvas c = holder.lockCanvas();
draw(c);
holder.unlockCanvasAndPost(c);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
@Override
public void run() {
while (running == true) {
// performs drawing to the canvas
if (!holder.getSurface().isValid()) {
continue;
}
Canvas c = holder.lockCanvas();
int x = 0;
int y = 0;
for (x = 0; x < grassCoords.length; x += grass.getWidth()) {
for (y = 0; y < grassCoords.length; y += grass.getHeight()) {
c.drawBitmap(grass, x, y, null);
}
}
holder.unlockCanvasAndPost(c);
}
}
}
ActivityClass.java
public class Test extends Activity {
MapLoader mapLoader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mapLoader = new MapLoader(this);
setContentView(mapLoader);
}
}
Any help or suggestions (even a link to an effective method) would be greatly appreciated!
Thanks,
Matt