【问题标题】:Drawing a circle with GDI graphics on WPF在 WPF 上用 GDI 图形绘制圆
【发布时间】:2017-05-28 01:14:48
【问题描述】:

我需要使用 GDI 图形在 WPF 中的表单上绘制一个圆圈。 我不能用 windows 窗体做到这一点,所以我添加了一个 using。 我无法使用 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();
}

这是错误:

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

【问题讨论】:

  • “我需要用 GDI 图形在 WPF 中的表单上绘制一个圆圈”。是什么原因?为什么不能使用 WPF Ellipse 控件?
  • 这是我的作业要求之一。我不知道为什么我的老师想要这个。 @克莱门斯
  • 我猜你误解了这个作业,你应该在 WinForms 中做这个。
  • 没有。我必须在 WPF @LarsTech 中进行
  • 他说:“使用 GDI Graphics 制作 WPF 中的新徽标。”

标签: c# wpf visual-studio drawing gdi


【解决方案1】:

你不能直接在 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));
                }
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 2022-08-06
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    相关资源
    最近更新 更多