2013-02-15 16 views
0

所以我在C#中創建了一個程序,它接受一張圖像並將其分割爲多個圖塊。我處於想要拍攝大圖像的位置,並將其切分成不同的圖塊並保存每個圖塊。我遇到的問題是它適用於第一塊瓷磚,但所有其他瓷磚都是空白的,我不知道爲什麼。這裏是我正在做Choping的代碼。在C#中用TextureBrush重複抽樣圖像

Graphics g; 
Image tempTile; 
TextureBrush textureBrush; 
int currRow = 1; 
int currCol = 1; 
int currX = 0; //Used for splitting. Initialized to origin x. 
int currY = 0; //Used for splitting. Initialized to origin y. 

//Sample our new image 
textureBrush = new TextureBrush(myChopImage); 

while (currY < myChopImage.Height) 
{ 
    while (currX < myChopImage.Width) 
    { 
     //Create a single tile 
     tempTile = new Bitmap(myTileWidth, myTileHeight); 
     g = Graphics.FromImage(tempTile); 

     //Fill our single tile with a portion of the chop image 
     g.FillRectangle(textureBrush, new Rectangle(currX, currY, myTileWidth, myTileHeight)); 

     tempTile.Save("tile_" + currCol + "_" + currRow + ".bmp"); 

     currCol++; 
     currX += myTileWidth; 

     g.Dispose(); 
    } 

    //Reset the current column to start over on the next row. 
    currCol = 1; 
    currX = 0; 

    currRow++; 
    currY += myTileHeight; 
} 

回答

1

你之所以有空白的磚是這一行:

g.FillRectangle(textureBrush, new Rectangle(currX, currY, myTileWidth, myTileHeight));

座標currX, currY指定從哪裏開始在瓷磚上繪製。在循環的第一次迭代之後,這些值超出了圖塊的邊界。

一個更好的方法可能是試圖通過使用Bitmap.Clone

while (currY < myChopImage.Height) 
{ 
    while (currX < myChopImage.Width) 
    { 
     tempTile = crop(myChopImage, new Rectangle(currX, currY, myTileWidth, myTileHeight)); 
     tempTile.Save("tile_" + currCol + "_" + currRow + ".bmp"); 

     currCol++; 
     currX += myTileWidth; 
    } 

    //Reset the current column to start over on the next row. 
    currCol = 1; 
    currX = 0; 

    currRow++; 
    currY += myTileHeight; 
} 

裁剪方法可能是這個樣子裁剪圖像:

private Bitmap crop(Bitmap bmp, Rectangle cropArea) 
{ 
    Bitmap bmpCrop = bmp.Clone(cropArea, bmp.PixelFormat); 
    return bmpCrop; 
} 
+0

是的,完美的作品,非常感謝你給我一個解決問題的辦法。 – Katianie 2013-02-15 19:24:53

0

難道你的情況:

g.FillRectangle(textureBrush, new Rectangle(currX, currY, myTileWidth, myTileHeight)); 

呼叫試圖填補在其邊界之外COORDS?

例如,瓷磚是10x10,第一次調用: g.FillRectangle(textureBrush,new Rectangle(0,0,10,10));

,並在第二個電話,你effeetively做

g.FillRectangle(textureBrush, new Rectangle(10, 0, 10, 10)); 

這是tempTile的邊界之外?

fillRectangle調用應該永遠是0,0,myTileWidth,myTileHeight,它是在你想改變textureBrush源位置。不確定你會如何做到這一點,也許使用翻譯轉換將其翻譯成相反的方向?

+0

我不beleve它去的範圍之外。對不起,你的答案可以幫助我。 – Katianie 2013-02-15 19:14:23

+0

你不相信?作爲一個測試,在該調用中嘗試currx/2,curry/2,看看它是否在保存的圖像中繪製了1/4的圖塊。 – 2013-02-15 19:41:30