2013-04-28 69 views
1

我正在關注一些Java2D教程,現在我正試圖在Canvas上繪製一個簡單的PNG。使用像素在畫布上繪製PNG;式?

我創建了一個BufferedImage,然後用pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();檢索像素數據。

於是,我打開我的PNG以類似的方式:

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

不過,我現在已經從spritePixels內容寫入pixels,並很爲難的公式:

假設高度和spriteImage的寬度將始終小於image,並且我將始終繪製到位置0,0,我相信我的公式將如下所示:

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

但是,我似乎無法弄清楚如何計算偏移量。這裏有什麼公式?

+0

你需要,如果你在upperleft角落繪製一個偏移? – arynaq 2013-04-28 20:23:29

+0

「偏移量」可能不是正確的詞。它是添加到索引中的值,以便較小的精靈可以插入到較大繪圖區域中的同一個掩碼上。 20x6上的4x4精靈將如下所示: 0→0,1→1,2→2→3→4→20→5→21。我試圖弄清楚這個翻譯的公式。 – 2013-04-28 20:54:00

+0

這是什麼樣的畫布?如果您只想將圖像繪製在另一個圖像上,則不需要轉到像素級別,只需使用其中一個Graphics.drawImage方法即可。 – lbalazscs 2013-04-29 16:05:59

回答

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