最大フォントサイズを使用して、画像に文字列を追加します画像の?C#の次のように私は、画像に2文字列を追加したい
例:テキストが大きすぎる場合、それは画像消灯::
This is Text That is too big
------------
------------
------------
--Other-----
最大フォントサイズを使用して、画像に文字列を追加します画像の?C#の次のように私は、画像に2文字列を追加したい
例:テキストが大きすぎる場合、それは画像消灯::
This is Text That is too big
------------
------------
------------
--Other-----
私は、各フォント・サイズのためにその寸法を算出することで、画像の中にいくつかのテキストに合わせて、私の以前のプロジェクトにこのスクリプトを書きました。フォントのサイズが画像の幅より大きい場合は、フォントサイズを0.1em小さくし、テキストが画像に収まるまで再試行します。ここで、コードは次のとおりです。ここで
public static string drawTextOnMarker(string markerfile, string text, string newfilename,Color textColor)
{
//Uri uri = new Uri(markerfile, UriKind.Relative);
//markerfile = uri.AbsolutePath;
//uri = new Uri(newfilename, UriKind.Relative);
//newfilename = uri.AbsolutePath;
if (!System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(newfilename)))
{
try
{
Bitmap bmp = new Bitmap(System.Web.HttpContext.Current.Server.MapPath(markerfile));
Graphics g = Graphics.FromImage(bmp);
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
StringFormat strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Center;
SolidBrush myBrush = new SolidBrush(textColor);
float fontsize = 10;
bool sizeSetupCompleted = false;
while (!sizeSetupCompleted)
{
SizeF mySize = g.MeasureString(text, new Font("Verdana", fontsize, FontStyle.Bold));
if (mySize.Width > 24 || mySize.Height > 13)
{
fontsize-= float.Parse("0.1");
}
else
{
sizeSetupCompleted = true;
}
}
g.DrawString(text, new Font("Verdana", fontsize, FontStyle.Bold), myBrush, new RectangleF(4, 3, 24, 8), strFormat);
bmp.Save(System.Web.HttpContext.Current.Server.MapPath(newfilename));
return newfilename.Substring(2);
}
catch (Exception)
{
return markerfile.Substring(2);
}
}
return newfilename.Substring(2);
}
は、迅速なソリューションです:あなたはTextRenderingHint.AntiAliasGridFit
または類似を使用している場合
using (Graphics g = Graphics.FromImage(bmp))
{
float width = g.MeasureString(text, font).Width;
float scale = bmp.Width/width;
g.ScaleTransform(scale, scale); //Simple trick not to use other Font instance
g.DrawString(text, font, Brushes.Black, PointF.Empty);
g.ResetTransform();
...
}
あなたのテキストは、常に100%の幅ではありませんが、私はそれはあなたのような問題ではないと思いますテキストだけがイメージに収まるようにしたい。
助けてくれてありがとう! – Aziz
'fontsize- = float.Parse(" 0.1 ");'、なぜ単に 'fontsize - = 1.0f'をしないのですか? – Matthew
私はC#を学んでいたので、それは私の最初の1ヶ月でした。 :)彼らは最後に同じことをします。たとえば、私はString mystring = ""を使用していました。私の友人はString mystring = String.Empty()を使用していました。どうしてこのようにしているのか聞いたら、彼はそれに慣れていたと言いました。異なる方法、同じ結果。 –
とBTW、mysize.width> 24 || mysize.height> 13はそこにハードコードされたイメージのサイズを定義します。あなたのニーズに合わせて変更する必要があります。 –