我在拼貼Bitmap
時遇到問題。我想要Bitmap
繪製到2D Array
中定義的座標。在SurfaceView Canvas上拼貼位圖
我想能夠讓我們說「草」到某些座標,「水等等」到其他座標。
我花了好幾天的時間試圖弄清楚這一點,並非常感謝任何見解。我只能得到Canvas
繪製1「草」Bitmap
,所以我覺得我的循環中有一個錯誤。我看過here和here,其中包括許多其他,並不希望每瓦都是相同的。這裏是我的代碼:
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);
}
}
任何幫助或建議(甚至一個鏈接到一個有效的方法),將不勝感激!
感謝,
馬特
謝謝你的鏈接和解釋。起初我無法理解一個二維數組。兩個答案都非常有幫助,並教會了我很多。謝謝你和@Geobits! – MattMatt