问题描述
我想在图像上添加一些文字。这是我的方法:
private Bitmap ConvertTextToImage(string text,FontFamily fontFamily,float fontSize,FontStyle fontStyle = FontStyle.Regular,StringFormat stringFormat = default,float MaxWidth = float.MaxValue,float MaxHeight = float.MaxValue,Color backgroundColor = default,Color foregroundColor = default)
{
Bitmap bitmap = new Bitmap(1,1);
Graphics graphics = Graphics.FromImage(bitmap);
if (stringFormat == default) stringFormat = new StringFormat();
if (backgroundColor == default) backgroundColor = Color.Transparent;
if (foregroundColor == default) foregroundColor = Color.Black;
Font font = new Font(fontFamily,fontSize,fontStyle);
SizeF stringSize = graphics.MeasureString(text,font,int.MaxValue,stringFormat);
while (stringSize.Width > MaxWidth || stringSize.Height > MaxHeight)
{
fontSize -= (float)0.1;
font = new Font(fontFamily,fontStyle);
stringSize = graphics.MeasureString(text,stringFormat);
}
bitmap = new Bitmap((int)stringSize.Width,(int)stringSize.Height);
graphics = Graphics.FromImage(bitmap);
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
graphics.Clear(backgroundColor);
int x = 0;
if (stringFormat.FormatFlags == StringFormatFlags.DirectionRightToLeft && stringFormat.Alignment == StringAlignment.Center)
x = (int)stringSize.Width / 2;
else if (stringFormat.FormatFlags == StringFormatFlags.DirectionRightToLeft) x = (int)stringSize.Width;
else if (stringFormat.Alignment == StringAlignment.Center) x += (int)stringSize.Width / 2;
graphics.DrawString(text,new SolidBrush(foregroundColor),x,stringFormat);
return bitmap;
}
//...
适合大字体或简单字体(例如Samim)。但是对于小尺寸的复杂字体(IranNastaliq),它会变成这样(棕色在主图像上,黑色由C#生成):
因此,我决定使用GraphicsPath.AddString
代替Graphics.DrawString
:
GraphicsPath graphicsPath = new GraphicsPath();
//...
graphicsPath.AddString(text,fontFamily,(int)fontStyle,fontSize * graphics.DpiY / 72,new Point(x,0),stringFormat);
graphics.FillPath(new SolidBrush(foregroundColor),graphicsPath);
但是结果仍然很糟糕:
如何渲染更高质量的文本?图像分辨率为2480x3508x300dpi,字体大小约为13。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)