【问题标题】:Drawing circle in canvas在画布上画圆圈
【发布时间】:2019-04-15 21:55:11
【问题描述】:

我最近开始学习 C# 编程。首先我画了一个简单的圆圈,但我对“char”-e.Graphics 有问题。我有必要的命名空间,如 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);

        }
    }
}
}

【问题讨论】:

  • e 不在draw.circle 的范围内...您需要将其作为参数传递给该方法。
  • 但是如果我添加 PaintEventArgs e 作为参数,我应该写什么到 draw.circle(iks, igrek, width, height), 什么变量?
  • public static void circle(int x, int y, int width, int height, RoutedEventArgs e) 将是新签名,并将其称为 draw.circle(iks, igrek, width, height, e);
  • 我想你可能需要花更多时间学习 C# 来了解参数。

标签: c# wpf graphics


【解决方案1】:

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

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 Name="MainCanvas">

</Canvas>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多