2017-08-12 129 views
0

我正在嘗試爲我的monogame項目創建一個使用Windows窗體的關卡編輯器,並且需要將基於小像素的圖像繪製到沒有質量損失的圖片框時進行縮放。在monogame中,當我需要這樣做時,我可以將繪圖類型設置爲PointClamp,然後每個像素按原樣繪製,而不是在縮放時進行像素化;我希望通過一個picturebox來做這樣的事情。現在它看起來像this但我更喜歡像this更清晰乾淨的圖像(第二個是它將出現在monogame中)。我沒有上傳任何代碼,但假設我從文件流中抓取了一個圖像,並使用位圖構造函數來擴展它(不要認爲這是相關的,但我會把它放在那裏)。CSharp Windows Form Picturebox繪製沒有質量損失的小圖像

Image croppedImage, image = tileMap.tileBox.Image; 
var brush = new SolidBrush(Color.Black); 

try { croppedImage = CropImage(image, tileMap.highlightedRect); } catch { 
    return; // If crop target is outside bounds of image then return 
} 

float scale = Math.Min(higlightedTileBox.Width/croppedImage.Width, higlightedTileBox.Height/image.Height); 

var scaleWidth = (int)(higlightedTileBox.Width * scale); 
var scaleHeight = (int)(higlightedTileBox.Height * scale); 

try { higlightedTileBox.Image = new Bitmap(croppedImage, new Size(scaleWidth, scaleHeight)); } catch { 
    return; // Image couldn't be scaled or highlighted tileBox couldn't be set to desired image 
} 

CropImage:

private static Image CropImage(Bitmap img, Rectangle cropArea) { 
    return img.Clone(cropArea, img.PixelFormat); 
} 

private static Image CropImage(Image img, Rectangle cropArea) { 
    return CropImage(new Bitmap(img), cropArea); 
} 

上面的代碼是我的當前方法在它的全部內容。 tileMap是一個窗體,tilebox是該窗體中的圖片框.image是在被剪裁爲用戶突出顯示的內容之前的完整spritesheet紋理。裁剪後,我嘗試將當前的圖片框(突出顯示的文本框)圖像設置爲裁剪圖像的放大版本。

+0

我們需要更多的代碼! – leAthlon

+1

好吧,給我一秒 –

+1

@leAthlon我已經添加了一些代碼:) –

回答

1

所以我通過嘗試了一下就得到了一個解決方案。 它看起來像按比例縮放圖像直接使用某種插值。 要嘗試Winforms支持的不同插值模式,我創建了一個小演示。您可以看到,每個標籤都包含InterpolationMode的名稱,後面跟着它的結果圖像。我使用的原始位圖是頂部的小圖。 enter image description here 從您的問題看,您似乎希望實現類似NearestNeighbour的內容。

以下代碼縮放bmp,結果存儲在bmp2中。試試如果這就是你想要的。考慮建立一個適當的實現,如果你使用這個解決方案(處置未使用的位圖等)。 我希望它有幫助。

 Bitmap bmp = new Bitmap("test.bmp"); 
     Bitmap bmp2; 
     Graphics g = Graphics.FromImage(bmp2=new Bitmap(bmp.Width * 2, bmp.Height * 2)); 
     g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; 
     g.DrawImage(bmp, 0, 0, bmp.Width * 2, bmp.Height * 2); 
     g.Dispose(); 
+0

Thnx我會試試看。剛花了一個小時試圖爲我的表單創建一個XNA控件,但這看起來更容易,所以我只是刪除它。 –

+1

是的,終於我得到了它的工作。 thnx這麼多:) –

+0

如果它是你想要的,考慮接受答案。 – leAthlon

相關問題