使用GDI+;在WPF应用中

使用GDI+;在WPF应用中,wpf,gdi+,Wpf,Gdi+,我正在用WPF应用程序编写一个程序,模拟生活中的游戏。 如何执行类似GDI+的图形操作来创建包含单元格网格的图像 (通常,在WinForms中,我会知道如何执行此操作) 编辑: 我使用了以下代码: WriteableBitmap wb = new WriteableBitmap(width * 5, height * 5, 100, 100, new PixelFormat(), new BitmapPalette(new List<Color> { Colo

我正在用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;
WriteableBitmap wb=newwriteablebitmap(宽*5,高*51000,新像素格式(),新位图调色板(新列表{Color.FromArgb(255,255,0,0)});
WritePixels(新的Int32Rect(0,0,5,5),新的IntPtr(),3,3);
背景。来源=wb;
背景是一个
System.Windows.Controls.Image
Control

您可以使用一个或多个WPF容器,例如网格或画布,其中包含许多矩形。很大程度上取决于游戏板的大小。WriteableBitmap可能更适合大型地图,而画布或网格可能更适合较小尺寸的地图


我认为你使用WriteableBitmap.WritePixel让事情变得更加艰难。使用形状或使用RenderTargetBitmap和DeviceContext进行绘图会更好

下面是一些关于如何使用此方法绘制的代码

MainForm的XAML:

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

根据需要调整图像的宽度/高度。所有绘图逻辑都应该在using语句中。您会发现DrawingContext上的方法比WritePixel更灵活、更容易理解。只要你想触发重画,就调用“DrawStuff”。

你想过使用WPF
网格和
矩形吗?你甚至可以得到更好的性能,因为一切都是基于向量的。我在另一篇文章中问过。谢谢:)它看起来很棒。我会在第二天早上检查(现在以色列时间是23:50),除了睡觉我什么都听不懂。。
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);
}