【问题标题】:Reset last draw graphics on text change在文本更改时重置上次绘制图形
【发布时间】:2014-07-09 13:16:53
【问题描述】:

我有一个用于绘制矩形的四个文本框,分别是 x、y、高度和宽度,我想在文本更改时绘制矩形,但是当我重置图像时没有绘制矩形 (`picturebox1.Image = bkp) 什么我做错了帮帮我,伙计们?

if (txtHeight.Text != "" && txtLeftMargin.Text != "" && txtTopMargin.Text != "" && txtWidth.Text != "")
            {
            pictureBox1.Image = bkp;
            Pen pen = new Pen(Color.Red);
            Graphics g = pictureBox1.CreateGraphics();
            g.DrawRectangle(pen, Convert.ToInt16(txtLeftMargin.Text), Convert.ToInt16(txtTopMargin.Text), Convert.ToInt16(txtHeight.Text), Convert.ToInt16(txtWidth.Text));

            }

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    尝试使用此代码:

       Image backgroundImage = (Image)bkp.Clone();
    
       using (Graphics gfx = Graphics.FromImage(backgroundImage))
       using (Pen pen = new Pen(Color.Red))
       {
          gfx.DrawRectangle(pen,
                            Convert.ToInt16(txtLeftMargin.Text),
                            Convert.ToInt16(txtTopMargin.Text),
                            Convert.ToInt16(txtHeight.Text),
                            Convert.ToInt16(txtWidth.Text));
       }
    
       pictureBox1.Image = backgroundImage;
    

    检查 "bkp" 图像是否为空且大于 1x1,否则您看不到任何东西。否则它应该工作。我使用 "Image.FromFile()" 对其进行了测试,我将 HDD 中的图像加载到 "backgroundImage" 变量中。图片的尺寸设置了最大绘制区域。

    【讨论】:

    • 实际上此代码不适用于文本更改,相同的代码在 Button Click 上工作正常!
    • 我制作了 4 个文本框,marginleft、margintop 和 posleft、posright,都链接到同一个“TextChanged”方法。除了“Image.FromFile”之外,我使用了与上面相同的代码。我还在读取值时使用了 Trim():marginleft.Text.Trim() != ""。我无法粘贴整个代码,因为 SO 给了我错误。 TextChanged 事件中还有其他问题会导致问题
    • 然后给我发邮件@faysal_ubit@yahoo.com
    【解决方案2】:

    和许多其他人一样,你的画法并不正确:

    您在winforms 中绘制的所有内容都必须在控件的paint 事件中绘制或从那里触发。所以你必须:

    • 将来自 textchange 事件的 Rectangle 的几何数据保存在某处(如果您正在这样做),
    • 将绘图放入paint 事件中(使用事件参数中的e.Graphics)和
    • 由invalidating控件触发..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多