C#测量字体大小的问题

最近写个程序很郁闷,用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));

        }

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



  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值