做過網頁的人都知道
網頁要有漂亮的字體只有幾種方式可選
1. 用Flash
2. 用圖片
3. HTML 5 + CSS3 + 字型檔
4. Web Font 服務 (付費)
舉凡要錢的檔案太大的都不是在啄雲的考慮之列
所以某天又求助Gooble大神之力找到了一些資料
出處倒忘了,知道的朋友煩請告知
這技巧主要靠Server提供所需字體的向量資料給前端Browser
前端Browser再利用SVG繪出
夠簡潔有力吧! 當然在Server端也要安裝所需字體才能運作
ASHX
--------------------------------------------------------------------------
using System;
using System.Web;
using System.Windows;
using Tufish.Utility;
public class example_1 : IHttpHandler {
public void ProcessRequest (HttpContext context) {
HttpResponse Response = context.Response;
HttpRequest Request = context.Request;
Response.ContentType = "image/svg+xml";
//華康魏碑體 標楷體
string text = (Request.QueryString["text"] == null) ? "無文字" : Request.QueryString["text"].ToString();
string fontFamily = (Request["font"] == null) ? "華康魏碑體" : Request["font"];
int textSize = (Request["size"] == null) ? 50 : Convert.ToInt32(Request["size"]);
string pathInfo = FontUtility.GetTextPath(text, fontFamily, textSize);
Response.Write(GetSVGTemplate(pathInfo));
}
private string GetSVGTemplate(string pathInfo,string strokeColor="black", string fillColor="red")
{
return string.Format(@"<svg width=""100%"" height=""100%"" xmlns=""http://www.w3.org/2000/svg"">
<path d=""{0}"" stroke=""{1}"" fill=""{2}""/></svg>",pathInfo,strokeColor,fillColor);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Library
--------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
namespace Tufish.Utility
{
public static class FontUtility
{
public static string GetTextPath(string str, string fontFamily, int nSize)
{
Typeface typeface = new Typeface(new FontFamily(fontFamily), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
FormattedText text = new FormattedText(str, new System.Globalization.CultureInfo("zh-tw"), FlowDirection.LeftToRight, typeface, nSize, Brushes.Black);
Geometry geo = text.BuildGeometry(new Point(0, 0));
PathGeometry path = geo.GetFlattenedPathGeometry();
string p = path.ToString();
return p.Substring(2); //前兩碼要去掉
}
}
}