SoftMask1.cs
// 完毕:
using System;
using System.IO;
using System.Drawing;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Pdf.Graphics;
using GrapeCity.Documents.Text;
using GrapeCity.Documents.Drawing;
using GCTEXT = GrapeCity.Documents.Text;
using GCDRAW = GrapeCity.Documents.Drawing;

namespace DsPdfWeb.Demos
{
    // 此示例演示了如何使用 GcPdfGraphics.SoftMask
    // 半透明绘制并指定剪切。
    public class SoftMask1
    {
        public int CreatePDF(Stream stream)
        {
            var doc = new GcPdfDocument();
            var page = doc.NewPage();
            var g = page.Graphics;

            var rc = Common.Util.AddNote(
                "GcPdfGraphics 有一个 SoftMask 属性,它允许使用 FormXObject 创建蒙版," +
                "",
                page);

            var rMask = new RectangleF(0, 0, 72 * 5, 72 * 2);
            var rDoc = new RectangleF(rc.Left, rc.Bottom + 36, rMask.Width, rMask.Height);

            var softMask = SoftMask.Create(doc, rDoc);
            var smGraphics = softMask.FormXObject.Graphics;
            smGraphics.FillEllipse(rMask, Color.FromArgb(128, Color.Black));
            smGraphics.DrawString("SOLID TEXT",
                new TextFormat() { Font = StandardFonts.HelveticaBold, FontSize = 52, ForeColor = Color.Black },
                new RectangleF(rMask.X, rMask.Y, rMask.Width, rMask.Height),
                TextAlignment.Center, ParagraphAlignment.Center, false);
            var rt = rMask;
            rt.Inflate(-8, -8);
            // 遮罩上的颜色并不重要,只有 Alpha 通道很重要:
            smGraphics.DrawEllipse(rt, Color.Red);

            g.SoftMask = softMask;
            g.DrawImage(GCDRAW.Image.FromFile(Path.Combine("Resources", "Images", "reds.jpg")), rDoc, null, ImageAlign.StretchImage);
            // 注意:它看起来像一些PDF查看器(例如内置浏览器查看器)
            // 除非事先重置掩码,否则不要正确处理更改软掩码
            // 分配一个新的,因此:
            g.SoftMask = SoftMaskBase.None;

            rDoc.Offset(0, rDoc.Height + 12);
            rDoc.Width = rc.Width;
            rDoc.Height = 36;
            rMask.Height = rDoc.Height;

            for (int alpha = 16; alpha <= 255; alpha += 32)
            {
                softMask = SoftMask.Create(doc, rDoc);
                smGraphics = softMask.FormXObject.Graphics;
                smGraphics.DrawString($"Text drawn on mask with alpha {alpha}.",
                    new TextFormat() { Font = StandardFonts.HelveticaBold, FontSize = 24, ForeColor = Color.FromArgb(alpha, Color.Black) },
                    new RectangleF(rMask.X, rMask.Y, rMask.Width, rMask.Height),
                    TextAlignment.Leading, ParagraphAlignment.Center, false);
                g.SoftMask = softMask;
                g.DrawImage(GCDRAW.Image.FromFile(Path.Combine("Resources", "Images", "reds.jpg")), rDoc, null, ImageAlign.StretchImage);
                g.SoftMask = SoftMaskBase.None;
                rDoc.Offset(0, rDoc.Height);
            }

            // 完毕:
            doc.Save(stream);
            return doc.Pages.Count;
        }
    }
}