2017-01-12 46 views
1

我需要用GDI图形在WPF中的表单上绘制一个圆。 我不能用windows窗体来做到这一点,所以我添加了一个使用。 我无法使用WPF的Elipse控件。我的老师告诉我这样做。在WPF上用GDI图形绘制圆形

这是我的代码:

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

+0

“我需要用GDI图形绘制的窗体上圆WPF”。是什么原因?为什么你不能使用WPF Ellipse控件? – Clemens

+0

这是我的任务的要求之一。我不知道为什么我的老师想要这个。 @Clemens – Gigitex

+1

我猜你误解了这个任务,你应该在WinForms中这样做。 – LarsTech

回答

2

你不能在WPF使用GDI直接,以达到你所需要的,请使用WindowsFormsHost。添加到System.Windows.Forms的WindowsFormsIntegration程序和参考文献,将其添加到XAML这样的(应该有东西在里面,比如面板或其他):

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

那么你的代码隐藏看起来就像这样,你就可以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声明这里的:

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