【发布时间】:2011-05-18 13:48:14
【问题描述】:
我需要计算显示文本的 Windows 窗体宽度。 表单宽度显然以像素为单位,因此您只想获取以像素为单位的文本宽度,但这不起作用:
animationForm.Width = TextRenderer.MeasureText(_caption, animationForm.Font).Width;
计算出的表单宽度太小(截断文本) - 这是怎么回事? MeasureText 使用像素,表单宽度以像素为单位。
这样效果更好,但我认为不正确:
animationForm.Width = (int)(_caption.Length * animationForm.Font.Size);
我们将不胜感激。
AnimationPic - 图片框, 标题设置在标签上
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace PrlSystems.MaimInvoicing.Forms
{
public partial class ProgressIndicatorForm : Form
{
private volatile bool _animating = false;
private Form _parent;
private string _caption = "";
private object _mutex = new object();
public ProgressIndicatorForm(Form parent)
{
InitializeComponent();
_parent = parent;
}
public string Caption
{
set { _caption = value; }
get { return _caption; }
}
public void StartAnimation()
{
lock (_mutex)
{
if (!_animating)
{
if (_parent != null)
{
_parent.Cursor = Cursors.WaitCursor;
_parent.Enabled = false;
}
_animating = true;
_SpawnAnimationThread();
}
}
}
public void StopAnimation()
{
lock (_mutex)
{
if (_animating)
{
_animating = false; // stop animation thread
if (_parent != null)
{
// restore parent form UI
_parent.Cursor = Cursors.Default;
_parent.Enabled = true;
_parent.Activate();
}
}
}
}
private void _SpawnAnimationThread()
{
Thread animationThread = new Thread(new ThreadStart(_Animate));
animationThread.Priority = ThreadPriority.Normal;
animationThread.IsBackground = true; // should terminate when application ends
animationThread.Start();
}
private void _Animate()
{
ProgressIndicatorForm animationForm = new ProgressIndicatorForm(_parent);
animationForm.CaptionLabel.Text = _caption;
animationForm.StartPosition = FormStartPosition.CenterScreen;
animationForm.TopMost = true;
animationForm.Width = _CalculateFormWidth(animationForm);
animationForm.Show();
while (_animating)
{
animationForm.CaptionLabel.Text = _caption;
animationForm.Width = _CalculateFormWidth(animationForm);
animationForm.BringToFront();
animationForm.Refresh();
}
animationForm.Close();
animationForm.Dispose();
}
private int _CalculateFormWidth(ProgressIndicatorForm animationForm)
{
int width = AnimationPic.Location.X + AnimationPic.Width +
TextRenderer.MeasureText(_caption, animationForm.Font).Width;
return width;
}
}
}
设计器中的图像:
【问题讨论】:
-
我要澄清一些我遗漏的东西,但这很重要。我也有动画图片。这是整个公式:int width = AnimationPic.Location.X + AnimationPic.Width + TextRenderer.MeasureText(_caption, animationForm.Font).Width;
标签: .net winforms forms graphics textrenderer