[英]Algorithm for fitting a string inside rectangle bounds
我正在嘗試編寫一種在矩形內擬合字符串的算法,但要注意的是每個字母都是另一個矩形,是實際字母的圖像,尺寸可以修改。 我當前的算法只是減小每個字母矩形的寬度和高度,直到總寬度(所有字母寬度的總和)小於主矩形的寬度。 這適合在單行中匹配字符串,但是換行是我的問題。
關於此主題的任何建議或參考將有所幫助。
我在.net C#環境中工作。
謝謝。
2)最終結果將使用自定義的渲染算法在圖像上渲染。
3)當前擬合算法:
do
{
ratio -= 0.05f;
FinalHeight = (int)(height * ratio);
totalWidth = GetTotalWidth(FinalHeight, text);
}
while (totalWidth > DestRectangle.Width);
int GetTotalWidth(int Height, char[] Text)
{
int totalWidth = 0;
int spaces = 0;
float letterHeight = 0;
foreach (char c in Text)
{
if (Char.IsWhiteSpace(c))
{
spaces++;
continue;
}
BoundingRect bounds = GetBoundingRectangle(c);
float letterWidth = bounds.Width;
letterHeight = bounds.Height;
int width = (int)((letterWidth * Height) / letterHeight);
totalWidth += width;
}
totalWidth += (int)(spaces * (totalWidth / Text.Length));
return totalWidth;
}
這似乎不是一個小問題。
我會嘗試以下攻擊方式:給定空格的位置,您可以枚舉所有可能的短語片段(例如“ This”,“ This is”,“ This is a”……“ random”,“ random text” “,...)。 對於N個單詞,有N.(N + 1)/ 2個可能性。
對於每個片段,計算其實際寬度。 然后確定自動換行,以使該寬度不會超過其他行。 這告訴您所需的行數。 (對於某些片段,這將是不可能的。)
例如,片段“隨機”應產生
This is
a random
text to
fit
和“隨機文本”
This is a
random text
to fit
現在,您有了一個邊界框,您可以說出什么縮放比例將其適合給定的矩形(垂直或水平填充)。
最后,保持最大縮放比例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.