c# - 在 Canvas 上画圆

我最近开始学习 C# 编程。首先我画了一个简单的圆圈,但我对“char”-e.Graphics 有疑问。我有必要的 namespace ,如 System.Drawing 和 System.windows.Form 程序与 WPF 应用程序有关。我希望能够输入尺寸并按下按钮绘制圆圈。

 namespace drawcircle
{
    /// <summary>
    /// Logika interakcji dla klasy MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window             
    {
        public MainWindow()
        {
            InitializeComponent();   
        }

        private void circle_Click(object sender, RoutedEventArgs e)
        {
            int iks = int.Parse(beginx.Text);
            int igrek = int.Parse(beginy.Text);
            int width = int.Parse(wid.Text);
            int height = int.Parse(hei.Text);

           draw.circle(iks, igrek, width, height);
        }


    class draw
    {
        public static void circle(int x, int y, int width, int height)
        {
            Pen color = new Pen(Color.Red);
            System.Drawing.SolidBrush fillblack = new System.Drawing.SolidBrush(Color.Black);

            Rectangle circle = new Rectangle(x, y, width, height);

            Graphics g = e.Graphics;
                g.DrawEllipse(color, circle);

        }
    }
}
}

最佳答案

首先,你已经为 winforms 创建了一个方法(如果你需要在 wpf 中导入 .Forms 你应该知道它错误的)。 SolidBrushColor.Red 之类的东西在 wpf 中不存在。在 winforms 中,解决方案将是一个非常小的变化:

窗体

调用方式:

draw.circle(10, 20, 40, 40, this.CreateGraphics());

类:

class draw
{
    public static void circle(int x, int y, int width, int height, Graphics g)
    {
        Pen color = new Pen(Color.Red);
        System.Drawing.SolidBrush fillblack = new System.Drawing.SolidBrush(Color.Black);
        Rectangle circle = new Rectangle(x, y, width, height);
        g.DrawEllipse(color, circle);
    }
}

对于 wpf 我会尝试做这样的事情:

WPF

调用方式:

draw.circle(10, 10, 100, 100, MainCanvas);

类:

class draw
{
    public static void circle(int x, int y, int width, int height, Canvas cv)
    {

        Ellipse circle = new Ellipse()
        {
            Width = width,
            Height = height,
            Stroke = Brushes.Red,
            StrokeThickness = 6
        };

        cv.Children.Add(circle);

        circle.SetValue(Canvas.LeftProperty, (double)x);
        circle.SetValue(Canvas.TopProperty, (double)y);
    }
}

XAML:
将您的网格更改为 Canvas 并将其命名为:

<Canvas Name="MainCanvas">

</Canvas>

https://stackoverflow.com/questions/44196638/

相关文章:

c# - 如何将数组作为 url 参数传递给 Azure Function

c# - 为什么 csv 文件在导出时不显示特殊字符?

php - Laravel 没有将模型加载到路由中

c# - C# 中的匿名类

php - mysqli_insert_id() 需要 1 个参数,0 在 CodeIgniter

three.js - 如何将边缘渲染为圆柱体?

python - 为什么 'WriteOnlyWorksheet' 对象没有属性 'cell' ?

css - PrimeNG - 如何改变 p-growl 风格

angular - 如何截断 typescript 中的数字

amazon-web-services - 使用 Laravel 5.3 的 Amazon SES