简体   繁体   English

绘制线在位图上以一定角度旋转

[英]Draw line rotated at an angle over bitmap

I am drawing a line from centre of png image to top in below code: 我在下面的代码中从png图像的中心到顶部画一条线:

    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. 这很好,我有一条距离图像中心90度的线。 Now what I need is instead of 90 degree perpendicular line, I would like to accept the degree from user input. 现在我需要的是代替90度垂直线,我想接受用户输入的程度。 If user enters 45 degree the line should be drawn at 45 degrees from centre of png image. 如果用户输入45度,则应该从png图像的中心以45度绘制线。

Please guide me in the right direction. 请指导我正确的方向。

Thanks 谢谢

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: 假设您在float angle中有所需的float angle您需要做的就是在绘制线条之前插入这三条线:

    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() ! 如果你想在没有旋转的情况下绘制更多东西,请调用g.ResetTranform()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM