在企業級應用開發中,電子公章的生成是常見需求。本文將示範如何利用 C# 的 GDI+ 繪圖功能,結合自定義的圓形文字佈局類,快速實現一個外觀專業的電子公章效果。文章將從核心代碼入手,逐步解析關鍵屬性設置與繪製邏輯。
以下是在按鈕點擊事件中完成公章繪製的完整代碼:
private void button1_Click(object sender, System.EventArgs e)
{
// 獲取繪圖面並初始化畫布
Graphics g = this.CreateGraphics();
g.Clear(Color.White);
// 啟用高質量渲染設置
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
// 公章基本參數
int radius = 200;
CircularTextualLayout ctl = new CircularTextualLayout();
ctl.Radius = radius;
Point location = new Point(50, 20);
ctl.Location = location;
// 文字內容與佈局設置
ctl.TextDrawing = "方正姚體方正姚體方正姚體方正姚體";
float arcAngle = 270;
ctl.ArcAngle = arcAngle;
// 計算起始角度,使文字居中分佈
ctl.AngleStart = -arcAngle / 2 + arcAngle / 2 / ctl.TextDrawing.Length;
// 字體與樣式
ctl.TextFontInner = new Font("方正姚體", radius / 3.2f);
ctl.RatioX = 0.6f; // 文字水平壓縮比例
ctl.BorderWidth = (int)(ctl.Radius / 40); // 邊框寬度
// 顏色設置(紅色為主,帶透明度)
Color stampRed = Color.FromArgb(250, Color.Red);
ctl.WordsColor = stampRed;
ctl.BorderColor = stampRed;
ctl.RectColor = stampRed;
// 執行繪製
ctl.Draw(g);
// 釋放資源
g.Dispose();
}
通過 CompositingQuality.HighQuality 和 SmoothingMode.HighQuality 確保公章邊緣平滑、無鋸齒,這對於正式文檔用印至關重要。
CircularTextualLayout 類封裝了複雜的三角函數計算,將文字沿圓弧均勻分佈。關鍵屬性說明:
採用「方正姚體」字體搭配標準印章紅(Color.FromArgb(250, Color.Red)),邊框寬度按半徑動態計算(Radius / 40),實現不同尺寸公章的自適應效果。
完整項目可參考附件圖片展示的最終效果。這個實現方案代碼量少、擴展性強,適合快速集成到各類辦公自動化系統中。