简体   繁体   中英

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:

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); doesn't draw anything on the screen. It seems 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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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