Drawing a circle with GDI graphics on WPF

不问归期 提交于 2019-12-24 11:37:52

问题


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:


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


来源:https://stackoverflow.com/questions/41621506/drawing-a-circle-with-gdi-graphics-on-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!