2

我从这个主题 GDI+ .NET 中发现了一个类似的问题:LinearGradientBrush 宽度超过 202 像素导致颜色环绕 但该解决方案对我不起作用。我也不能问那个话题。请看一下。这是我的代码:

public partial class Form1 : Form {

    int ShadowThick = 10;
    Color ShadowColor = Color.Gray;
    int width;
    int height;

    public Form1() {
        InitializeComponent();
        width = this.Width - 100;
        height = this.Height - 100;
    }

    private void Form1_Paint(object sender, PaintEventArgs e) {
        //e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
        GraphicsPath shadowPath = new GraphicsPath();
        LinearGradientBrush shadowBrush = null;
        // draw vertical shadow
        shadowPath.AddArc(this.width - this.ShadowThick, this.ShadowThick, this.ShadowThick,
            this.ShadowThick, 180, 180);
        shadowPath.AddLine(this.width, this.ShadowThick * 2, this.width,
            this.height - this.ShadowThick);
        shadowPath.AddLine(this.width, this.height - this.ShadowThick,
            this.width - this.ShadowThick, this.height - this.ShadowThick);
        shadowPath.CloseFigure();
        // declare the brush
        shadowBrush = new LinearGradientBrush(PointF.Empty,
            new PointF(this.ShadowThick + 1, 0), this.ShadowColor, Color.Transparent);
        //shadowBrush = new LinearGradientBrush(PointF.Empty,
        //    new PointF(this.ShadowThick + 1, 0), this.ShadowColor, Color.Transparent);

        //e.Graphics.DrawPath(Pens.Black, shadowPath);

        e.Graphics.PixelOffsetMode = PixelOffsetMode.Half;
        e.Graphics.FillPath(shadowBrush, shadowPath);
    }

}

我希望从左到右从暗到亮,但请参阅:

在此处输入图像描述

我试图画一个阴影,我坚持这一点。

4

1 回答 1

2

正如汉斯在下面评论的那样,画笔坐标需要与路径匹配,所以不要这样:

shadowBrush = new LinearGradientBrush(PointF.Empty,
    new PointF(this.ShadowThick + 1, 0), this.ShadowColor, Color.Transparent);

它应该是:

new LinearGradientBrush(new Point(this.width - this.ShadowThick, 0),
                        new Point(this.width, 0),
                        this.ShadowColor, Color.Transparent);

此外,您应该处理您创建的图形对象。我还将您的画笔更改为仅使用 Point 而不是 PointF,因为您不处理浮点数。

这是您重新编写的代码:

  e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
  e.Graphics.PixelOffsetMode = PixelOffsetMode.Half;
  using (GraphicsPath shadowPath = new GraphicsPath()) {
    shadowPath.StartFigure();
    shadowPath.AddArc(this.width - this.ShadowThick, this.ShadowThick, 
        this.ShadowThick, this.ShadowThick, 180, 180);
    shadowPath.AddLine(this.width, this.ShadowThick * 2, this.width,
        this.height - this.ShadowThick);
    shadowPath.AddLine(this.width, this.height - this.ShadowThick,
        this.width - this.ShadowThick, this.height - this.ShadowThick);
    shadowPath.CloseFigure();
    using (var shadowBrush = new LinearGradientBrush(
        new Point(this.width - this.ShadowThick, 0),
        new Point(this.width, 0),
        this.ShadowColor, Color.Transparent)) {
      e.Graphics.FillPath(shadowBrush, shadowPath);
    }
  }
于 2013-04-24T21:11:10.053 回答