在.Net中向图像上绘制带描边的文本

3

我目前在使用 .Net 中的 System.Drawing.Graphics.DrawString() 方法,在图像上绘制文本,然后将其保存为新文件:

// define image file paths
string sourceImagePath = HttpContext.Current.Server.MapPath("~/img/sourceImage.jpg");
string destinationImagePath = HttpContext.Current.Server.MapPath("~/img/") + "finalImage.jpg";

// create new graphic to draw to
Bitmap bm = new Bitmap(200, 200);
Graphics gr = Graphics.FromImage(bm);

// open and draw image into new graphic
System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(sourceImagePath, true);
gr.DrawImage(sourceImage, 0, 0);
sourceImage.Dispose();

// write "my text" on center of image
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;

PrivateFontCollection fontCollection = new PrivateFontCollection();
fontCollection.AddFontFile(HttpContext.Current.Server.MapPath("~/fonts/HelveticaNeueLTStd-BlkCn.ttf"));
// prototype (1)
gr.DrawString("my text", new Font(fontCollection.Families[0], 14, FontStyle.Bold), new SolidBrush(Color.FromArgb(255, 255, 255)), 100, 0, sf);
fontCollection.Dispose();

// save new image
if (File.Exists(destinationImagePath))
{
    File.Delete(destinationImagePath);
}
bm.Save(destinationImagePath);
bm.Dispose();
gr.Dispose();

这种在图像上添加文本的方法似乎不能提供一种(我所知道的)给文本添加描边的方式。例如,我真正需要做的是在图像上书写的文本上添加一个特定颜色的2px描边。

如何使用 .Net Framework <= v3.5 实现这一点?

3个回答

7

所有文本都有笔画

如果你指的是轮廓,那么你可以创建一个GraphicsPath并使用AddString添加字符串,然后使用DrawPath而不是msdn上示例中使用的FillPath来描边路径。

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        // Create a GraphicsPath object.
        GraphicsPath myPath = new GraphicsPath();

        // Set up all the string parameters.
        string stringText = "Sample Text";
        FontFamily family = new FontFamily("Arial");
        int fontStyle = (int)FontStyle.Italic;
        int emSize = 96;
        Point origin = new Point(20, 20);
        StringFormat format = StringFormat.GenericDefault;

        // Add the string to the path.
        myPath.AddString(stringText,
            family,
            fontStyle,
            emSize,
            origin,
            format);

        //Draw the path to the screen.
        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
        e.Graphics.FillPath(Brushes.BlanchedAlmond, myPath);
        e.Graphics.DrawPath(new Pen(Brushes.Azure, 2), myPath);
    }

如果您说的“stroke”是指划掉文字, 那么请使用删除线字体样式。

如果您说的“stroke”是指衬线字体, 那么请使用其他字体。


非常好用!我选择的一件事是先调用DrawPath,然后再调用FillPath。这样绘制的路径不会覆盖实际填充的路径,更像是描边。谢谢! - Rafe

0

不确定这是否正是您要寻找的,但尝试在您的代码中使用LinearGradientBrush而不是SolidBrush

我不确定您在这个问题中所说的“描边”是什么意思,但如果您想让第7行和第8行上的所有像素都变成红色,您可以使用System.Drawing.TextureBrush而不是SolidBrush。您需要创建一个宽度为1像素且足够高以适应您的字体的Bitmap(除了第7行和第8行为红色外,其余均为黑色),然后使用以此Bitmap作为参数的TextureBrush构造函数。


0
有点取巧,但您可以将两组文本层叠在一起,下层略微放大。这种方法可能不适用于所有字体,但值得一试。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接