using (var bitmap = new Bitmap("1.jpg"))
using (var graphics = bitmap.GetAdvancedGraphics())
{
var brush = new SolidBrush(RgbColor.Black);
var text =
@"中文字体12:23:45 123456";
var boundedText = new PlainText(text, graphics.CreateFont("Tahoma", 30f), brush);
var position = new PointF(5, boundedText.GetBlackBox().Height + 5);
var p1 = position;
p1.X -= 1;
boundedText.Position = p1;
graphics.DrawText(boundedText);
p1 = position;
p1.Y -= 1;
boundedText.Position = p1;
graphics.DrawText(boundedText);
p1 = position;
p1.X += 1;
boundedText.Position = p1;
graphics.DrawText(boundedText);
p1 = position;
p1.Y += 1;
boundedText.Position = p1;
graphics.DrawText(boundedText);
p1 = position;
boundedText.Position = p1;
boundedText.Brush = new SolidBrush(RgbColor.White);
graphics.DrawText(boundedText);
bitmap.Save(@"DrawFormattedText.png");
}
The above code doesn't work if there are Chinese characters in string, The "Tahoma" font does support Chinese character, how to draw Chinese character?
Well actually Tahoma font doesn't contain Chinese characters. Nevertheless font fallback and font linking techniques allows to render Chinese characters switching to another font if neccessary. So all supported characters are rendered using a base font (Tahoma) and other characters are rendered using font with full support of characters (for example Arial Unicode).
The approach can be demonstrated using the following code:
var text = @"<span style='font-name:Arial Unicode MS'>中文字体</span>12:23:45 123456";
var boundedText = new PlainText(text, graphics.CreateFont("Tahoma", 30f), brush);
So in order to display Chinese characters you need either to draw image using some text which includes all approporaite characters:
var text = @"中文字体12:23:45 123456"
var boundedText = new PlainText(text, graphics.CreateFont("Arial Unicode MS", 30f), brush)
Alternatively you can preprocess text and draw Chinese characters using fallback font:
public static string ProcessFontFallback(string str, string fontName)
{
bool chinese = false;
var sb = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
var c = str[i];
//Chinese characters
if (c >= 0x4E00 && c <= 0x9FA5)
{
if (!chinese)
{
sb.AppendFormat(@"<span style='font-name:{0}'>", fontName);
chinese = true;
}
}
else if (chinese)
{
sb.Append(@"</span>");
chinese = false;
}
sb.Append(c);
}
if (chinese)
sb.Append(@"</span>");
return sb.ToString();
}
var text = ProcessFontFallback(@"中文字体12:23:45 123456", "Arial Unicode MS");
var boundedText = new PlainText(text, graphics.CreateFont("Tahoma", 30f), brush);
The Graphics Mill SDK support neither font fallback nor font linking natively. Nevertless we plan to add it in the further releases (Aurigma Bug #0020975). Currently please use the above approaches.