在WPF上用GDI图形绘制一个圆圈

时间:2017-01-12 19:35:30

标签: c# wpf visual-studio drawing gdi

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

这是我的代码:

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

这就是错误:

  

主窗口'不包含' CreateGraphics'的定义没有扩展方法' CreateGraphics'接受类型' MainWindow'的第一个参数。可以找到(你错过了使用指令或程序集引用吗?)

1 个答案:

答案 0 :(得分:2)

您无法直接在WPF中使用GDI,以实现您的需求,请使用WindowsFormsHost。添加对System.Windows.Forms和WindowsFormsIntegration的引用,将它添加到xaml中(应该包含一些内容,如Panel或其他内容):

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

然后你的代码隐藏将会是这样的,你就可以了

    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声明是个好主意:

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));
                }
            }
相关问题