2011-03-03 78 views
2

我在模擬生命遊戲的WPF應用程序中編寫程序。 我如何使GDI +像圖形操作一樣進行預成型以創建包含單元網格的圖像?在WPF應用程序中使用GDI +

(通常,在WinForms中,我會知道如何執行此操作)。

編輯: 我用這個代碼:

  WriteableBitmap wb = new WriteableBitmap(width * 5, height * 5, 100, 100, new PixelFormat(), new BitmapPalette(new List<Color> { Color.FromArgb(255, 255, 0, 0) })); 
     wb.WritePixels(new Int32Rect(0, 0, 5, 5), new IntPtr(), 3, 3); 
     Background.Source = wb; 

背景是System.Windows.Controls.Image控制

+0

你有沒有想過使用WPF'Grid'和'Rectangle's?你甚至可能會獲得更好的性能,因爲一切都是基於矢量的 – madd0 2011-03-03 15:22:51

回答

1

我覺得你使用WriteableBitmap.WritePixel使事情變得更難自己。使用Shapes繪圖或使用RendterTargetBitmap和DeviceContext您會有更好的時間。

下面是關於如何使用此方法繪製的一些代碼。

的MainForm的XAML:

<Grid> 
    <Image Name="Background" 
      Width="200" 
      Height="200" 
      VerticalAlignment="Center" 
      HorizontalAlignment="Center" /> 
</Grid> 

MainForm中的代碼隱藏:

private RenderTargetBitmap buffer; 
private DrawingVisual drawingVisual = new DrawingVisual(); 

public MainWindow() 
{ 
    InitializeComponent();    
} 

protected override void OnRender(DrawingContext drawingContext) 
{ 
    base.OnRender(drawingContext); 
    buffer = new RenderTargetBitmap((int)Background.Width, (int)Background.Height, 96, 96, PixelFormats.Pbgra32); 
    Background.Source = buffer; 
    DrawStuff(); 
} 

private void DrawStuff() 
{ 
    if (buffer == null) 
     return; 

    using (DrawingContext drawingContext = drawingVisual.RenderOpen()) 
    { 
     drawingContext.DrawRectangle(new SolidColorBrush(Colors.Red), null, new Rect(0, 0, 10, 10)); 
    } 

    buffer.Render(drawingVisual); 
} 

調整到任何你想要的圖片的寬度/高度。所有的繪圖邏輯都應該在using語句中。您會發現DrawingContext上的方法比WritePixel更靈活,更易於理解。每當你想觸發重繪時調用「DrawStuff」。

+0

謝謝:)它看起來很棒。我會在第二天早上(現在是以色列的23:50)檢查它,現在除了睡覺外什麼都不能理解.. – 2011-03-03 21:57:23

+0

非常感謝! – 2011-03-04 06:57:47

2

你可以使用一個WriteableBitmap或使用WPF容器,如電網或帆布帶了很多長方形在它。很大程度上取決於遊戲板的大小。一個WriteableBitmap可能更適合一個巨大的地圖,而一個畫布或網格對於較小的尺寸可能更容易。

Is this what you are looking for?

+0

我嘗試使用writableBitmap。請參閱編輯。 – 2011-03-03 15:41:49

+0

那麼,爲什麼沒有這樣的工作? – 2011-03-03 15:47:19

+0

http://stackoverflow.com/questions/5185420/calling-the-writeablebitmap-writepixels-method/5186049#5186049 我在另一篇文章中提到過。 – 2011-03-03 20:34:56