1

I'm following a couple of Java2D tutorials, and am now trying to draw a simple PNG on a Canvas.

I create a BufferedImage and then retrieve the pixel data with pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();.

Then, I load my PNG in a similar fashion:

spriteImage = ImageIO.read(Shape.class.getResourceAsStream(path));
width = spriteImage .getWidth();
height = spriteImage .getHeight();
spritePixels = spriteImage .getRGB(0, 0, width, height, null, 0, width);

However, I now have to write the contents from spritePixels into pixels, and am stumped on the formula:

Assuming the height and width of spriteImage will always be less than image, and that I'll always be drawing into position 0,0 I believe my formula will look something like this:

for (int spriteIndex = 0; spriteIndex < spritePixels.length; spriteIndex ++)
  pixels[spriteIndex + offset] = spritePixels[x];

However, I can't seem to figure out how to calculate the offset. What's the formula, here?

4

1 回答 1

1

首先,您必须将索引映射到较小图像中的行/列,然后找出它对应于另一个图像中的行/列。这应该有效:

public class OffsetCalc {
private int rows;
private int cols;
private int rowsOther;
private int colsOther;

public OffsetCalc(int rows, int cols, int rowsOther, int colsOther) {
    this.rows = rows;
    this.cols = cols;
    this.rowsOther = rowsOther;
    this.colsOther = colsOther;
}

public void getOffset(int i) {
    int col = i % cols;
    int row = i / cols;
    System.out.println("i=" + i + " @row,col: " + row + "," + col);

    int other = (col) + (row * rowsOther);
    System.out.println("i=" + i + " @Other image: " + other);
}

public static void main(String[] args) {
    OffsetCalc calc = new OffsetCalc(4, 4, 20, 6);
    for (int i = 0; i <= 14; i++) {
        calc.getOffset(i);
    }
}
}

输出:

i=0 @row,col: 0,0
i=0 @Other image: 0
i=1 @row,col: 0,1
i=1 @Other image: 1
i=2 @row,col: 0,2
i=2 @Other image: 2
i=3 @row,col: 0,3
i=3 @Other image: 3
i=4 @row,col: 1,0
i=4 @Other image: 20
i=5 @row,col: 1,1
i=5 @Other image: 21
i=6 @row,col: 1,2
i=6 @Other image: 22
i=7 @row,col: 1,3
i=7 @Other image: 23
i=8 @row,col: 2,0
i=8 @Other image: 40
i=9 @row,col: 2,1
i=9 @Other image: 41
i=10 @row,col: 2,2
i=10 @Other image: 42
i=11 @row,col: 2,3
i=11 @Other image: 43
i=12 @row,col: 3,0
i=12 @Other image: 60
i=13 @row,col: 3,1
i=13 @Other image: 61
i=14 @row,col: 3,2
i=14 @Other image: 62
于 2013-04-28T22:48:17.170 回答