【问题标题】:how to draw a line on a image?如何在图像上画线?
【发布时间】:2012-07-09 07:30:04
【问题描述】:

我想在 bmp 图像上画一条线,该线将传递给使用 C# 中的 drawline 方法的方法

public void DrawLineInt(Bitmap bmp)
{

Pen blackPen = new Pen(Color.Black, 3);

int x1 = 100;
int y1 = 100;
int x2 = 500;
int y2 = 100;
// Draw line to screen.
e.Graphics.DrawLine(blackPen, x1, y1, x2, y2);
}

这给出了一个错误。所以我想知道如何在这里包含绘画事件 (PaintEventArgs e)

还想知道我们调用drawmethod时如何传递参数? 例子

DrawLineInt(Bitmap bmp);

这给出以下错误 “当前上下文中不存在名称‘e’”

【问题讨论】:

  • “这给出了一个错误”。什么错误?

标签: c# system.drawing


【解决方案1】:

“在 BMP 图像上画一条线,该线将传递给 C# 中使用 drawline 方法的方法”

PaintEventArgs e 会建议您在对象的“绘制”事件期间执行此操作。由于您在方法中调用它,因此您不需要在任何地方添加 PaintEventArgs e。

要在方法中执行此操作,请使用@BFree 的答案。

public void DrawLineInt(Bitmap bmp)
{
    Pen blackPen = new Pen(Color.Black, 3);

    int x1 = 100;
    int y1 = 100;
    int x2 = 500;
    int y2 = 100;
    // Draw line to screen.
    using(var graphics = Graphics.FromImage(bmp))
    {
       graphics.DrawLine(blackPen, x1, y1, x2, y2);
    }
}

重绘对象时会引发“Paint”事件。欲了解更多信息,请参阅:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.paint.aspx

【讨论】:

  • 您还应该在使用完笔后将其丢弃。或者把它放在using(var blackPen = new Pen(Color.Black, 3)) 块中。
【解决方案2】:

您需要像这样从Image 获取Graphics 对象:

using(var graphics = Graphics.FromImage(bmp))
{
   graphics.DrawLine(...)
}

【讨论】:

  • @user1150071 “我需要在代码中的任何位置添加 PaintEventArgs e 吗?”简短的回答,不。长答案,请参阅下面的帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2016-05-23
  • 2013-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多