我有兩個一維數組,其中包含像素顏色數據,代表不能轉換爲二維數組用於我的目的的圖像。其中一個數組表示一個spritesheet,另一個表示一個遊戲畫布。我試圖從spritesheet中拖出32x32的方形精靈,並在特定的x-y座標處放置在畫布上。問題在於我沒有認真思考如何將精靈從spritesheet移植到畫布上。通過一維數組移動圖像分部
據我所知,每個x,y位置對應於1維數組中的一個索引,並且每個32x32精靈的數據在它所在的1維數組內是非連續的,但是我很難出現用適當的轉換公式。
這是鏈接到包含進行中的代碼的文件: https://github.com/srwaggon/caffeine/blob/development/src/caffeine/view/screen/Screen.java
package caffeine.view.screen;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import caffeine.view.Spritesheet;
public class Screen extends Canvas {
private static final long serialVersionUID = -2226504463501471657L;
protected Spritesheet sprites = new Spritesheet("sprites.png");
int xOffset = 0, yOffset = 0;
final int WIDTH = 600;
final int HEIGHT = WIDTH * 10/16;
private final BufferedImage screen = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB);
private final int[] pixels = ((DataBufferInt) screen.getRaster()
.getDataBuffer()).getData();
int ticks = 0;
public final Dimension getPreferredSize() {
return new Dimension(WIDTH, HEIGHT);
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(1);
return;
}
Graphics gfx = bs.getDrawGraphics();
gfx.drawImage(screen, 0, 0, null);
gfx.dispose();
bs.show();
}
public void render(int spriteID, int x, int y) {
//x -= xOffset;
//y -= yOffset;
// copy the pixel data
for (int row = 0; row < 32; row++) {
for (int col = 0; col < 32; col++) {
int sheet = (spriteID * 32 + row) * 32 + col;
int canvas = (32 * (row + y)) + col + x;
// if the indices are valid, attempt to copy.
if (canvas >= 0 && canvas < pixels.length && sheet >= 0
&& sheet < sprites.pixels.length) {
pixels[canvas] = sprites.pixels[sheet];
}
}
}
}
}
轉換旨在落入渲染方法。