我發現沒有循環的更好的解決方案。在這種方法中,我們計算當前寬度和目標寬度之間的比率。如果這個比率乘以當前的字符串長度,我們得到一個好的子串點。
string GetSubStringToWidth(string orgText, int width, Font font)
{
int orgWidth = TextRenderer.MeasureText(orgText, font).Width;
float ratio = (float)width/orgWidth;
int length = (int)(orgText.Length * ratio);
if (length >= orgText.Length) return orgText;
else if (length <= 0) return "";
else
{
//May be more sensitive if we go right or left one unit because of letter unequalities
int mid = Math.Abs(width - TextRenderer.MeasureText(orgText.Substring(0, length), font).Width);
int right = Math.Abs(width - TextRenderer.MeasureText(orgText.Substring(0, length + 1), font).Width);
int left = Math.Abs(width - TextRenderer.MeasureText(orgText.Substring(0, length - 1), font).Width);
int i = Math.Min(Math.Min(mid, right), left);
int point = 0;
if (i == mid)
point = length;
else if (i == right)
point = length + 1;
else
point = length - 1;
return orgText.Substring(0, point);
}
}
這是什麼類型的應用程序?使用適當的標籤 –
這是一個Windows窗體應用程序 –
除非您使用固定寬度的字體,否則所有字符將具有不同的寬度,因此您需要做這樣的事情。 – TaW