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

Draw line rotated at an angle over bitmap

我在下面的代码中从 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;
    }

这很好用,我有一条与图像中心成 90 度角的线。 现在我需要的不是 90 度垂直线,我想接受用户输入的度数。如果用户输入 45 度,则应在距 png 图像中心 45 度的位置绘制线。

请指导我正确的方向。

谢谢

假设您在 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));

如果你想在没有旋转调用的情况下绘制更多内容 g.ResetTranform() !