GDI+ 文本测量方法

15 篇文章 4 订阅

背景

图形类 Graphics 是 GDI+的核心,它提供绘制图形、图像和文本的各种方法。Graphics 中使用 DrawString 方法在指定位置绘制文本或者在一个指定矩形内绘制文本。

通过调用 Graphics 对象的 MeasureString 方法,可以对文本的绘制区域进行计算。

计算文本所需矩形范围

void DemoGDI::DrawUser(HDC hdc)
{
  Graphics graphics(hdc);//构造 Graphics 对象
  SolidBrush solidBrush(Color::Blue);
  Font font(L"宋体", 24, FontStyleRegular, UnitPixel);

  QString m_txt = "在Qt中使用GD+示例";
  
  graphics.DrawString(m_txt.toStdWString().c_str(), -1, &font, PointF(20, 20), nullptr, &solidBrush);

  Pen m_pen(Color::Black);
  RectF boundRect;
  graphics.MeasureString(m_txt.toStdWString().c_str(), -1, &font, PointF(20, 20), &boundRect);
  graphics.DrawRectangle(&m_pen, boundRect);
    
}

在这里插入图片描述

指定区域宽度计算所需高度

void DemoGDI::DrawUser(HDC hdc)
{
  Graphics graphics(hdc);//构造 Graphics 对象
  SolidBrush solidBrush(Color::Blue);
  Font font(L"宋体", 24, FontStyleRegular, UnitPixel);

  QString m_txt = "在Qt中使用GD+示例";

  RectF layoutRect(20, 20, 90, 0);//高度设置为0
  
  Pen m_pen(Color::Black);
  RectF boundRect;
  graphics.MeasureString(m_txt.toStdWString().c_str(), -1, &font, layoutRect, &boundRect);
  graphics.DrawRectangle(&m_pen, boundRect);

  graphics.DrawString(m_txt.toStdWString().c_str(), -1, &font, boundRect, nullptr, &solidBrush);
    
}

在这里插入图片描述

通过路径计算所需矩形范围

void DemoGDI::DrawUser(HDC hdc)
{
  Graphics graphics(hdc);//构造 Graphics 对象
  SolidBrush solidBrush(Color::Blue);
  Font font(L"宋体", 24, FontStyleRegular, UnitPixel);

  QString m_txt = "在Qt中使用GD+示例";
  graphics.DrawString(m_txt.toStdWString().c_str(), -1, &font, PointF(20, 20), nullptr, &solidBrush);

  Pen m_pen(Color::Black);
  RectF boundRect;
  Gdiplus::GraphicsPath graphicsPath;
  FontFamily fontFamily(L"宋体");
  graphicsPath.AddString(m_txt.toStdWString().c_str(), -1, &fontFamily, font.GetStyle(), font.GetSize(), PointF(20, 20), nullptr);  
  graphicsPath.GetBounds(&boundRect);

  graphics.DrawRectangle(&m_pen, boundRect);
}

在这里插入图片描述

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值