how to draw a line on a image?

依然范特西╮ 提交于 2019-11-26 08:29:48

问题


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

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 )

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

DrawLineInt(Bitmap bmp);

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


回答1:


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

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.

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

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:

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




回答2:


You need to get the Graphics object from the Image like so:

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


来源:https://stackoverflow.com/questions/11402862/how-to-draw-a-line-on-a-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!