我正在尝试实现一种功能,以显示适合该区域的最大字符像素数。
示例:区域大小为:(100x20像素)需要显示的字符串是:volutpa commodo diam
注意:字符串中的每个字符(包括空格)必须具有相同的像素大小(例如6x6 px),才能填充整个区域,并且字符串中的单词不得拆分/分割。手动完成所有操作后,我能够确定字符的最大像素大小(不拆分/划分单词)为8x8 px。每个字符必须具有相同的像素大小。
Example。在这里,您可以看到我正在尝试实现的“手工制作”图像。整个布局代表区域大小(100x20 px),黑框代表字符像素大小(8x8 px)。如果我使用(9x9像素或更多)的字符大小,文本将不适合;如果我使用(7x7像素或更少)的字符,则将有太多的空白。
在C#中实现此目标的最佳方法是什么?
String sentence = "volutpa commodo diam";
int width = 100; // 100 px
int height = 20; // 20 px
int pixelSize = height / 2; // Starting pixel size (10)
int maxLines = height / pixelSize; // Max. available lines in the area
int currentLine = 1; // Starting line
string[] words = sentence.Split(' '); // Splitting words from the sentence. words[1] = volutpa, words[2] = commodo, words[3] = diam
// Length of the words
for (int i = 0; i < words.Length; i++)
{
Console.WriteLine("Word " + i + " length: " + words[i].Length * pixelSize);
}
我现在已经做到了,但无法弄清楚如何继续。我将不胜感激。
这是我的建议,GetPixelSize()
方法将递归检查所需的行数,pixelSize
将从行数中派生。
private static void Main(string[] args)
{
String sentence = "volutpa commodo diam";
int width = 100; // 100 px
int height = 20; // 20 px
string[] words = sentence.Split(' '); // Splitting words from the sentence. words[1] =
// check if we can use one line (and it will be 20X20 or 2 lines and it will be 10X10,
int pixelSize = GetPixelSize(words, height,width);
int maxLines = height / pixelSize; // Max. available lines in the area
// Length of the words
for (int i = 0; i < words.Length; i++)
{
Console.WriteLine("Word " + i + " length: " + words[i].Length * pixelSize);
}
Console.ReadLine();
}
private static int GetPixelSize(string[] words, int height,int width,int linesneeded = 1)
{
var h = height / linesneeded;
var lines = linesneeded;
var accumulate = 0;
for (int i = 0;i< words.Length;i++)
{
accumulate += words[i].Length * h;
// add space if it is not the last word
if (i < words.Length - 1)
{
accumulate += h;
}
// more line needed - call recursivaly until we get the number of lines needed
if (accumulate / linesneeded > width)
{
return GetPixelSize(words, height, width, linesneeded+1);
}
}
return h;
}