使用 System.Drawing 勾勒文本? [英] Outline text with System.Drawing?

查看:37
本文介绍了使用 System.Drawing 勾勒文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码.有没有一种简单的方法可以给我正在写的文本加上大纲?

I have the following code. Is there an easy way to put an outline on the text I am writing?

 var imageEncoder = Encoder.Quality;
 var imageEncoderParameters = new EncoderParameters(1);
 imageEncoderParameters.Param[0] = new EncoderParameter(imageEncoder, 100L);

 var productImage = GetImageFromByteArray(myViewModel.ProductImage.DatabaseFile.FileContents);
 var graphics = Graphics.FromImage(productImage);

 var font = new Font("Segoe Script", 24);
 var brush = Brushes.Orange;

 var container = new Rectangle(myViewModel.ContainerX, myViewModel.ContainerY,                                      myViewModel.ContainerWidth,                                              myViewModel.ContainerHeight);

 var stringFormat = new StringFormat {Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center};

 graphics.DrawString(customizationText, font, brush, container, stringFormat);

推荐答案

是的.使用以下调用序列代替 DrawString:

Yes. Instead of DrawString, use the following sequence of calls:

  • new GraphicsPath (creates an empty GraphicsPath)
  • GraphicsPath.AddString (the GraphicsPath object now represents the outline of the text)
  • Graphics.DrawPath (draws the outline in any Pen you want)

如果您需要将 GraphicsPath.AddStringGraphics.DrawString 一起使用,则需要转换字体大小,因为 Graphics.DrawString 需要点大小"而 GraphicsPath.AddString 需要em 大小".转换公式很简单emSize = g.DpiY * pointSize/72.

If you need to use GraphicsPath.AddString alongside Graphics.DrawString, you need to convert the font sizes, because Graphics.DrawString expects "point size" while GraphicsPath.AddString expects "em size". The conversion formula is simply emSize = g.DpiY * pointSize / 72.

这是一个代码示例:

// assuming g is the Graphics object on which you want to draw the text
GraphicsPath p = new GraphicsPath(); 
p.AddString(
    "My Text String",             // text to draw
    FontFamily.GenericSansSerif,  // or any other font family
    (int) FontStyle.Regular,      // font style (bold, italic, etc.)
    g.DpiY * fontSize / 72,       // em size
    new Point(0, 0),              // location where to draw text
    new StringFormat());          // set options here (e.g. center alignment)
g.DrawPath(Pens.Black, p);
// + g.FillPath if you want it filled as well

这篇关于使用 System.Drawing 勾勒文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆