显卡的DrawString以精确地放置文本上System.Label [英] Graphics DrawString to Exactly Place Text on a System.Label

查看:188
本文介绍了显卡的DrawString以精确地放置文本上System.Label的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经覆盖了的OnPaint 标签控制方法VS2008:

I have overridden the OnPaint method of my Label control in VS2008:

void Label_OnPaint(object sender, PaintEventArgs e) {
  base.OnPaint(e);
  dim lbl = sender as Label;
  if (lbl != null) {
    string Text = lbl.Text;
    e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    if (myShowShadow) { // draw the shadow first!
      e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(myShadowColor), myShadowOffset, StringFormat.GenericDefault);
    }
    e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(lbl.ForeColor), 0, 0, StringFormat.GenericDefault);
  }
}

这工作,但我真的想了解如何以垂直和水平居中的文字。我听说 MeasureString()的方法,但我的文本会使事情复杂化,因为它可能包括分页符。

This works, but I really want to find out how to center the text both vertically and horizontally. I've heard of the MeasureString() method, but my "Text" complicates matters because it could include page breaks.

可能有人指导我如何做到这一点?

Could someone guide me with how to do this?

推荐答案

下面的是我目前使用的代码,

Here is the code i'm using at the moment,

SizeF size;
string text = "Text goes here";
size = e.Graphics.MeasureString(text, font);
x = (lineWidth / 2) - (size.Width / 2);
y = top;
e.Graphics.DrawString(text, font, Brushes.Black, x, y);

这篇关于显卡的DrawString以精确地放置文本上System.Label的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆