【问题标题】:How to pass parameters in C# GDI+ Windows Desktop如何在 C# GDI+ Windows 桌面中传递参数
【发布时间】:2022-01-02 20:38:32
【问题描述】:

我对学习 C# GDI+ 很感兴趣,并在 Google 上搜索了许多教程。我正在尝试创建一个具有两个文本框控件和一个按钮的简单 Windows 窗体。我只想在一个文本框中放置一个长度尺寸,在另一个文本框中放置一个高度尺寸,单击按钮并让应用程序使用这两个输入的尺寸在窗口上绘制矩形。迄今为止,我所能做的就是找到将矩形参数硬编码到 Form_Load 和 Form_Paint 中的教程。我将如何从文本框中获取用户输入并传递它们以使应用程序刷新并在按钮单击时绘制矩形? 如果需要更多信息,请告诉我。 提前感谢您的知识!

public partial class Form1 : Form
{
    Bitmap drwBitmap;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Graphics graphicObj;
        drwBitmap = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height,
           System.Drawing.Imaging.PixelFormat.Format24bppRgb);
        graphicObj = Graphics.FromImage(drwBitmap);
        graphicObj.Clear(Color.White);
        Pen myPen = new Pen(System.Drawing.Color.Red, 3);
        Rectangle rectObj;
        rectObj = new Rectangle(10, 10, 100, 200);
        graphicObj.DrawEllipse(myPen, rectObj);
        graphicObj.Dispose();
    }

    private void Form1_Paint(object sender, PaintEventArgs e, Graphics graphicsObj)
    {
        Graphics graphicsObj1 = graphicsObj;
        graphicsObj1.DrawImage(drwBitmap, 0, 0, drwBitmap.Width, drwBitmap.Height);
        graphicsObj.Dispose();
    }

【问题讨论】:

  • A) 在 FormLoad 事件中绘制/绘制任何内容没有意义,因为它还没有显示,所以 Windows B) 您从哪里获得 Paint 事件的签名? Windows 将传递一个有效 图形对象作为PaintEventArgs 的一部分使用该对象。 C)您还应该查看 using 块语句....对于初学者

标签: c# gdi+


【解决方案1】:

当前的方法很奇怪,因为它直接绘制到表单上。很难修改,因为位图是在早期创建的,然后必须以某种方式进行更改。此外,不需要位图。

更好的方法是创建自定义控件:

public class EllipseControl : Control
{
    private float m_ellipseWidth = 200;
    private float m_ellipseHeight = 120;

    public float EllipseWidth
    {
        get { return m_ellipseWidth; }
        set
        {
            m_ellipseWidth = value;
            Invalidate();
        }
    }

    public float EllipseHeight
    {
        get { return m_ellipseHeight; }
        set
        {
            m_ellipseHeight = value;
            Invalidate();
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        var graphics = e.Graphics;
        using Pen pen = new Pen(System.Drawing.Color.Red, 3);
        graphics.DrawEllipse(pen, 0, 0, EllipseWidth, EllipseHeight);
    }
}

然后可以将此控件放置在表单上。它有两个属性:EllipseWidthEllipseHeight

在按钮单击的事件处理程序中,您可以从文本字段中获取值并将它们设置在椭圆控件上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-06
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2011-08-04
    • 2018-04-03
    相关资源
    最近更新 更多