C#测量字体大小的问题

来源:互联网 发布:mysql nvl函数用法 编辑:程序博客网 时间:2024/05/18 18:45

最近写个程序很郁闷,用Gdi+ 的MeasureString测量的宽度好高度都要比DrawString 绘制的高。所以索性采用GraphicsPath来进行绘图,后面测试的结果的是满意的,但是发现字体又偏小,终于找到了解决方案:如下

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics graphics = e.Graphics;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            GraphicsPath path = new GraphicsPath();
            
            FontFamily family = new FontFamily("楷体");
            Font font = new Font(family, 300, FontStyle.Bold);
            StringFormat stringFormat = new StringFormat();
            stringFormat.Alignment = StringAlignment.Near;
            string str = "8E";

            float emSize = graphics.DpiY * font.Size / 72;
            path.AddString(str, family, (int)font.Style, emSize, new PointF(0, 0), stringFormat);
            RectangleF rect = path.GetBounds();
            e.Graphics.FillPath(Brushes.Black, path);

            graphics.DrawRectangle(new Pen(Color.Red), rect.X, rect.Y, rect.Width, rect.Height);
            
            // 得到测量宽度
            float width = rect.Width;
            // 得到测量高度
            float height = rect.Height;


            // 以下测试MeasureString,测试结果是长度要长于文字
            SizeF size = graphics.MeasureString(str, font, new PointF(0, 0), stringFormat);
            graphics.DrawString(str, font, new SolidBrush(Color.Red),new PointF(0, height + 10),stringFormat );
            //graphics.DrawEllipse(new Pen(Color.Red), new RectangleF(0,height +5, size.Width, size.Height));
            graphics.DrawRectangle(new Pen(Color.Red), new Rectangle(0, (int)height + 5, (int)size.Width, (int)size.Height));

        }

以上涵盖两种测绘方式的结果



0 0
原创粉丝点击