开发者

using GDI+ in WPF application

开发者 https://www.devze.com 2023-02-14 19:49 出处:网络
I\'m writing a program in WPF application that simulates the game of life. How can I preform GDI+ like graphics operations to create an Image that contains the grid of cells?

I'm writing a program in WPF application that simulates the game of life. How can I preform GDI+ like graphics operations to create an Image that contains the grid of cells?

(Normally, in WinForms, I would have know how to do this operation).

Edit: I used this code:

            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;

Background is a System.Windows.Controls.Image Control


You could use a WriteableBitmap or use a WPF container such as a Grid or Canvas with a lot of rectangles in it. A lot depends on the size of the gameboard. A WriteableBitmap might be better suited for a huge map and a canvas or grid might be easier for smaller sizes.

Is this what you are looking for?


I think you're making things harder on yourself by using WriteableBitmap.WritePixel. You'll have a much better time drawing with Shapes or using RendterTargetBitmap and a DeviceContext.

Here's some code on how you would draw using this method.

MainForm's XAML:

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

MainForm's Code-Behind:

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);
}

Adjust the Width/Height of the Image to whatever you desire. All of your drawing logic should be inside of the using statement. You'll find the methods on DrawingContext are much more flexible and easier to understand than WritePixel. Call "DrawStuff" whenever you want to trigger a redraw.

0

精彩评论

暂无评论...
验证码 换一张
取 消