c#图片处理之:在图片上打上文字
以前讨论过在一张图片上加上另一张图片,说难也不难,基本上只要知道利用GDI+提供的DrawImage函数就可以了。现在需要在图片上打上文字,其实也很简单。贴图用DrawImage,那么贴文字当然就是DrawString啦。
//============================设置文字==============================
/**//// <summary>
/// 设置文字
/// </summary>
/// <param name="b">原始图片</param>
/// <param name="txt">显示的文字</param>
/// <param name="x">在图片上的x坐标</param>
/// <param name="y">在图片上的y坐标</param>
/// <returns>输出后的图片</returns>
public static Bitmap KiSetText(Bitmap b, string txt, int x, int y)
...{
if (b == null)
...{
return null;
}
Graphics g = Graphics.FromImage(b);
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
// 作为演示,我们用Arial字体,大小为32,红色。
FontFamily fm = new FontFamily("Arial");
Font font = new Font(fm, 32, FontStyle.Regular, GraphicsUnit.Pixel);
SolidBrush sb = new SolidBrush(Color.Red);
g.DrawString(txt, font, sb, new PointF(x, y));
g.Dispose();
return b;
}
/**//// <summary>
/// 设置文字
/// </summary>
/// <param name="b">原始图片</param>
/// <param name="txt">显示的文字</param>
/// <param name="x">在图片上的x坐标</param>
/// <param name="y">在图片上的y坐标</param>
/// <returns>输出后的图片</returns>
public static Bitmap KiSetText(Bitmap b, string txt, int x, int y)
...{
if (b == null)
...{
return null;
}
Graphics g = Graphics.FromImage(b);
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
// 作为演示,我们用Arial字体,大小为32,红色。
FontFamily fm = new FontFamily("Arial");
Font font = new Font(fm, 32, FontStyle.Regular, GraphicsUnit.Pixel);
SolidBrush sb = new SolidBrush(Color.Red);
g.DrawString(txt, font, sb, new PointF(x, y));
g.Dispose();
return b;
}
当然,实际使用中当然希望自己灵活设置字体、颜色、大小等信息。很简单,根据上面的原理自己再改写一个函数就行了。比如,
public static Bitmap KiSetText(Bitmap b, string txt, string TextFont,int TextSize, Color c, int x, int y)
...{
if (b == null)
...{
return null;
}
Graphics g = Graphics.FromImage(b);
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
FontFamily fm = new FontFamily(TextFont);
Font font = new Font(fm, TextSize, FontStyle.Regular, GraphicsUnit.Pixel);
SolidBrush sb = new SolidBrush(c);
g.DrawString(txt, font, sb, new PointF(x, y));
g.Dispose();
return b;
}
...{
if (b == null)
...{
return null;
}
Graphics g = Graphics.FromImage(b);
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
FontFamily fm = new FontFamily(TextFont);
Font font = new Font(fm, TextSize, FontStyle.Regular, GraphicsUnit.Pixel);
SolidBrush sb = new SolidBrush(c);
g.DrawString(txt, font, sb, new PointF(x, y));
g.Dispose();
return b;
}
如果我们利用VS2005提供的字体控件,还可以简化成
public static Bitmap KiSetText(Bitmap b, string txt, Font font,Color c,int x, int y)
{
if (b == null)
{
return null;
}
Graphics g = Graphics.FromImage(b);
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
SolidBrush sb = new SolidBrush(c);
g.DrawString(txt, font, sb, new PointF(x, y));
g.Dispose();
return b;
}
是不是很简单:)