2011-03-03 53 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