Draw line rotated at an angle over bitmap

孤人 提交于 2019-12-02 11:47:27

问题


I am drawing a line from centre of png image to top in below code:

    private string ProcessImage(string fileIn)
    {
        var sourceImage = System.Drawing.Image.FromFile(fileIn);
        var fileName = Path.GetFileName(fileIn);
        var finalPath = Server.MapPath(@"~/Output/" + fileName);

        int x = sourceImage.Width / 2;
        int y = sourceImage.Height / 2;
        using (var g = Graphics.FromImage(sourceImage))
        { 
            g.DrawLine(new Pen(Color.Black, (float)5), new Point(x, 0), new Point(x, y));
        }
        sourceImage.Save(finalPath);

        return @"~/Output/" + fileName;
    }

This works fine and I have a line that is 90 degrees from centre of image. Now what I need is instead of 90 degree perpendicular line, I would like to accept the degree from user input. If user enters 45 degree the line should be drawn at 45 degrees from centre of png image.

Please guide me in the right direction.

Thanks


回答1:


Let's assume you have the angle you want in a float angle all you need to do is to insert these three lines before drawing the line:

    g.TranslateTransform(x, y);   // move the origin to the rotation point 
    g.RotateTransform(angle);     // rotate
    g.TranslateTransform(-x, -y); // move back

    g.DrawLine(new Pen(Color.Black, (float)5), new Point(x, 0), new Point(x, y));

If you want to draw more stuff without the rotation call g.ResetTranform() !



来源:https://stackoverflow.com/questions/36015098/draw-line-rotated-at-an-angle-over-bitmap

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