由于项目需要,需生成svg格式文字图片,网上的文档较少,在一番查阅之后成功实现。现记录下来,方便以后自己查阅,以及需要的人也可当做参考,水平不高,少喷。
主要运用到GitHub开源项目: svg.net
不墨迹直接上代码:
主方法:
/// <summary>
/// 依据参数生成svg文本,返回svg文件路径
/// </summary>
/// <param name="FontFamily">字体名,须和illustrator中英文字体一致,
/// 否则在其中字体不会生效</param>
/// <param name="FontText">文本内容</param>
/// <param name="fontSize">字体大小 pt</param>
/// <param name="color">英文color</param>
/// <param name="isvertical">是否垂直</param>
/// <returns></returns>
public static string DrawText(string FontFamily, string FontText, int fontSize = 30,string color="balck",bool isvertical=false)
{
SvgDocument svgDocument = new SvgDocument();
string Name = "文本" + DateTime.Now.ToString("yyyyMMdd HHmmss");
SvgDocument document = new SvgDocument();
Svg.SvgText text = new Svg.SvgText()
{
Font = FontFamily,//字体
Text = FontText,//文字内容
FontSize = fontSize,
ID = Name
};
if (isvertical) //垂直文本处理
{
text.Rotate = "-90";//字符方向
text.AddStyle("writing-mode", "tb", 2);//文本方向
svgDocument.Width = text.Bounds.Height;//垂直文本助理后宽度互换
svgDocument.Height = text.Bounds.Width;
text.X.Add(-text.Bounds.Y / 2);
}
else
{
text.X.Add(-text.Bounds.X);
text.Y.Add(-text.Bounds.Y);
svgDocument.Width = text.Bounds.Width;//将文档大小设置为和字体一致
svgDocument.Height = text.Bounds.Height;
}
//文本转向的另一种方法 该方法在illustrator中不起作用,但在谷歌浏览器中生效
//SvgTransformCollection transforms = new SvgTransformCollection();
//transforms.Add(new SvgRotate(90));
//svgDocument.Transforms=transforms;
//text.Transforms = transforms;
text.AddStyle("fill", color, 1);//填充颜色
svgDocument.Children.Add(text);//将文本对象放进文档中
try
{
string path = @"C:\Users\09056722\Desktop\test.svg";
svgDocument.Write(path);//保存
return path;
}
catch (Exception e)
{
throw new Exception("处理合成文字svg出错,错误信息:" + e.Message);
}
}
测试代码:
static void Main(string[] args)
{
// SvgText.RenderRectAlignedText(new SvgGraphics(), 90, 90, new Font("微软雅黑",12));
//SvgText.DrawTest();
SvgText.DrawText("STHupo","你猜我在干啥你想干啥",40,"Green",true);
}
效果图:
多多指导。