在C#中,使用Graphics.DrawString
方法可以實現文本陰影效果。以下是一個簡單的示例,展示了如何使用TextRenderer
類在WinForms應用程序中繪制帶有陰影的文本:
using System;
using System.Drawing;
using System.Windows.Forms;
public class TextWithShadow : Form
{
private string text = "Hello, World!";
private Font font = new Font("Arial", 20);
private Color shadowColor = Color.Black;
private float shadowOffset = 3;
public TextWithShadow()
{
this.Text = "Text with Shadow";
this.Size = new Size(400, 200);
this.StartPosition = FormStartPosition.CenterScreen;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// Draw the shadow
using (Graphics g = e.Graphics)
{
g.DrawString(text, font, shadowColor, new PointF(this.Width + shadowOffset, this.Height + shadowOffset));
}
// Draw the text
using (Graphics g = e.Graphics)
{
g.DrawString(text, font, Brushes.Black, new PointF(this.Width / 2, this.Height / 2));
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TextWithShadow());
}
}
在這個示例中,我們創建了一個名為TextWithShadow
的WinForms窗體類。我們在OnPaint
方法中繪制了帶有陰影的文本。首先,我們使用Graphics.DrawString
方法繪制陰影文本,然后再次使用相同的方法繪制正常文本。陰影文本的偏移量由shadowOffset
變量控制。