首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C# 生成逼真印章效果:透明背景、顏色不均勻、疊加底層文字的完整方案

     編輯:程式設計疑難解答

需求拆解

  1. 形狀:圓形邊框 + 五角星 + 文字 (單位名稱、編號等)。
  2. 質感:顏色不均勻 (模擬油墨濃淡)、邊緣模糊、有磨損噪點。
  3. 透明度:背景完全透明,疊加在文檔上可見底層內容。
  4. 輸出:Bitmap 對象或保存為 PNG (保留 Alpha 通道)。

核心實現步驟

1. 創建透明畫布

int size = 300; // 印章直徑像素
Bitmap stamp = new Bitmap(size, size, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(stamp)) {
    g.Clear(Color.Transparent); // 關鍵:透明背景
    g.SmoothingMode = SmoothingMode.AntiAlias; // 抗鋸齒
}

2. 繪製基礎幾何體

using (Graphics g = Graphics.FromImage(stamp)) {
    // 外圓
    using (Pen pen = new Pen(Color.FromArgb(200, 180, 0, 0), 8)) { // 深紅、半透明
        g.DrawEllipse(pen, 4, 4, size - 8, size - 8);
    }
    // 五角星 (中心)
    DrawStar(g, size/2, size/2, 50, Color.FromArgb(200, 180, 0, 0));
    // 文字 (繞圓或水平)
    DrawCircularText(g, "單位名稱", size/2, size/2, 100, Color.Red);
}

3. 核心質感:隨機透明化模擬不均勻

// 像素級處理:隨機將部分像素設置為透明/半透明
Random rnd = new Random();
for (int y = 0; y < size; y++) {
    for (int x = 0; x < size; x++) {
        Color c = stamp.GetPixel(x, y);
        if (c.A > 0) { // 非透明像素
            // 30% 概率降低透明度,模擬油墨缺失
            if (rnd.NextDouble() < 0.3) {
                int newAlpha = (int)(c.A * (0.3 + rnd.NextDouble() * 0.5)); // 30%-80%
                stamp.SetPixel(x, y, Color.FromArgb(newAlpha, c.R, c.G, c.B));
            }
            // 5% 概率完全透明 (磨損)
            else if (rnd.NextDouble() < 0.05) {
                stamp.SetPixel(x, y, Color.Transparent);
            }
        }
    }
}

性能優化:使用 Bitmap.LockBits 直接操作內存,避免 GetPixel/SetPixel 極慢。

4. 疊加到目標文檔

public void StampOnDocument(string docPath, string outputPath, Point location) {
    using (Image doc = Image.FromFile(docPath))
    using (Graphics g = Graphics.FromImage(doc))
    using (Bitmap stamp = GenerateStamp()) {
        g.DrawImage(stamp, location); // 直接疊加,透明背景自動混合
        doc.Save(outputPath, ImageFormat.Png); // 或 PDF 需用 PdfSharp 等庫
    }
}

進階質感技巧 (可選)

  • 高斯模糊:stamp = GaussianBlur(stamp, 1.5f); 模擬油墨擴散。
  • 紋理疊加:載入紙張/織物紋理圖,用 Multiply 混合模式疊加。
  • 邊緣羽化:印章外緣漸變透明,PathGradientBrush 實現。

總結

C# 生成逼真印章核心流程:透明畫布 → 矢量繪製基礎形狀 → 像素級隨機透明化模擬質感 → LockBits 加速 → DrawImage 疊加。關鍵在Format32bppArgb 保證透明通道與隨機演算法模擬真實油墨缺陷。代碼模塊化後,可輕松擴展不同樣式、尺寸、顏色的印章生成器。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved