C# 如何在图像上画一条线?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11402862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:44:30  来源:igfitidea点击:

how to draw a line on a image?

c#system.drawing

提问by user1150071

i want to draw a line on a bmp image which is pass into a method using drawline method in C#

我想在 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);
}

this give a error.So i want to know how to include paint event here (PaintEventArgs e )

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

and also want to know how to pass parameters when we calling drawmethod? example

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

DrawLineInt(Bitmap bmp);

this give the following error "The name 'e' does not exist in the current context "

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

采纳答案by Tom

"Draw a line on a bmp image which is pass into a method using drawline method in C#"

“在 bmp 图像上绘制一条线,该线被传递到使用 C# 中的 drawline 方法的方法中”

PaintEventArgs e would suggest that you are doing this during the "paint" event for an object. Since you are calling this in a method, then no you do not need to add PaintEventArgs e anywhere.

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

To do this in a method, use @BFree's answer.

要在方法中执行此操作,请使用@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);
    }
}

The "Paint" event is raised when the object is redrawn. For more information see:

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

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

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

回答by BFree

You need to get the Graphicsobject from the Imagelike so:

您需要GraphicsImage这样的对象中获取对象:

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