简体   繁体   English

C#Graphics.DrawString和Graphics.ScaleTransform冲突?

[英]C# Graphics.DrawString and Graphics.ScaleTransform conflict?

When projecting a unit sphere onto a plane, I want to also draw the original and projected coordinates. 将单位球体投影到平面上时,我还要绘制原始坐标和投影坐标。 Since I've never stopped using WinForms, I am using GDI+ to draw the image: 由于我从未停止过使用WinForms,因此我使用GDI +绘制图像:

private void btnRender_Click(object sender, EventArgs e)
{
    tabMain.SelectedTab = tabRender;
    var tangent = new Vector3D(0.0, 0.0, -1.0);
    var xsize = 2048;
    var ysize = 2048;
    var pen = new Pen(Color.Maroon, (float)(1 / xsize));
    var font = new Font("Arial", 10);
    var brush = new SolidBrush(Color.Black);

    var bmp = new Bitmap(xsize, ysize);
    using (var g = Graphics.FromImage(bmp)) {
        g.TranslateTransform(xsize / 2, ysize / 2);
        g.ScaleTransform(xsize, ysize);
        foreach (var v in hull.Vertices) {
            foreach (var f in v.VoronoiFaces) {
                var pts = f.Vertices.Select(v1 => (PointF)Projector.Stereographic(v1, tangent)).ToArray();
                g.DrawPolygon(pen, pts);
            }
            var pt = (PointF)Projector.Stereographic(v.Vertex, tangent);
            var str = String.Format("{0}->{1}", v.Vertex, pt);
            g.DrawString(str, font, brush, pt);
        }
    }
    picRender.Width = xsize;
    picRender.Height = ysize;
    picRender.Image = bmp;
}

When I render the image, g.DrawString(str, font, brush, pt); 当我渲染图像时, g.DrawString(str, font, brush, pt); doesn't draw anything on the screen. 在屏幕上不画任何东西。 It seems g.ScaleTransform(xsize, ysize); 看来g.ScaleTransform(xsize, ysize); is the culprit, since when I remove it, all the text gets drawn. 是罪魁祸首,因为当我删除它时,所有文本都会被绘制。 I guess it scales the text up and the text gets pushed off the screen. 我猜它会放大文本,并且文本会被推离屏幕。 Is there a way to draw the text so that its size is not transformed, but its position is? 有没有一种方法可以绘制文本,以便不改变其大小,但可以改变其位置? When I divide the font size by the scale factor, GDI+ throws an exception. 当我将字体大小除以比例因子时,GDI +会引发异常。

Should I roll with a custom coordinate transformation instead of the builtin one? 我应该使用自定义坐标变换而不是内置坐标变换吗? Or should I switch to a different graphics library? 还是应该切换到其他图形库? Which one? 哪一个?

Yes, you can draw the text such that only the position is transformed, and not the size. 是的,您可以绘制文本,以便仅改变位置而不改变大小。 Don't use ScaleTransform. 不要使用ScaleTransform。 Instead, multiply your text point coordinates by the scaling factors. 而是将文本点坐标乘以缩放系数。 Or create a Matrix and use that to multiply. 或创建一个矩阵并将其相乘。 The exception you describe is probably from trying to set a font size to 0. 您描述的异常可能是由于尝试将字体大小设置为0。

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

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