Drawing a circle with GDI graphics on WPF

2019-07-29 18:56发布

I need to draw with GDI graphics a circle on my form in WPF. I can't do this with windows forms, so i have added a using. I can not use the Elipse controls from WPF. My teacher told me to do this like this.

This is my code:

public void MakeLogo()
{
    System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Green);
    System.Drawing.Graphics formGraphics = this.CreateGraphics();
    formGraphics.FillEllipse(myBrush, new System.Drawing.Rectangle(0, 0, 200, 300));
    myBrush.Dispose();
    formGraphics.Dispose();
}

And this is the error:

MainWindow' does not contain a definition for 'CreateGraphics' and no extension method 'CreateGraphics' accepting a first argument of type 'MainWindow' could be found (are you missing a using directive or an assembly reference?)

1条回答
beautiful°
2楼-- · 2019-07-29 19:26

You can't use GDI within WPF directly, to achieve what you need, please use WindowsFormsHost. Add references to System.Windows.Forms and WindowsFormsIntegration, add it to xaml like this (should have something inside, like Panel or whatever):

<Window x:Class="WpfApplication1.MainWindow"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                xmlns:local="clr-namespace:WpfApplication1"
                mc:Ignorable="d"
                xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
                Title="MainWindow" Height="350" Width="525">
        <!--whatever goes here-->
        <WindowsFormsHost x:Name="someWindowsForm">
            <wf:Panel></wf:Panel>
        </WindowsFormsHost>
        <!--whatever goes here-->
    </Window>

Then your code-behind will look like this and you'll be ok

    SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Green);
    Graphics formGraphics = this.someWindowsForm.Child.CreateGraphics();
    formGraphics.FillEllipse(myBrush, new System.Drawing.Rectangle(0, 0, 200, 300)); 
    myBrush.Dispose();
    formGraphics.Dispose();

UPD: good idea to make use of using statement here:

using (var myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Green))
            {
                using (var formGraphics = this.someForm.Child.CreateGraphics())
                {
                    formGraphics.FillEllipse(myBrush, new System.Drawing.Rectangle(0, 0, 200, 300));
                }
            }
查看更多
登录 后发表回答