我最近开始学习 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
你应该知道它错误的)。 SolidBrush
和 Color.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 我会尝试做这样的事情:
调用方式:
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/