在WPF上用GDI图形绘制圆

问题描述:

我需要在WPF中的窗体上使用GDI图形绘制一个圆圈. 我无法使用Windows表单执行此操作,因此我添加了一个用法. 我不能使用WPF中的Elipse控件.我的老师叫我这样做.

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.

这是我的代码:

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

这是错误:

MainWindow'不包含'CreateGraphics'的定义,找不到可以接受类型为'MainWindow'的第一个参数的扩展方法'CreateGraphics'(您是否缺少using指令或程序集引用?)

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?)

您不能直接在WPF中使用GDI,要实现所需的功能,请使用

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:在此处使用using语句的好主意:

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