【问题标题】:Drawing transparent image on WinForms在 WinForms 上绘制透明图像
【发布时间】:2014-08-28 17:31:16
【问题描述】:

我需要在 WinForms 上绘制透明的 PNG 图像。我有一个基类:

public abstract class BaseSkinable : Panel
    {
        protected BaseSkinable()
        {
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
        }

    protected abstract void OnDraw(Graphics graphics);


    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x00000020;
            return cp;
        }
    }

    protected override void OnPaintBackground(PaintEventArgs e) { }

    protected override void OnPaint(PaintEventArgs e)
    {

        e.Graphics.TextRenderingHint =
            System.Drawing.Text.TextRenderingHint.AntiAlias;
        e.Graphics.InterpolationMode =
            System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        e.Graphics.PixelOffsetMode =
            System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        e.Graphics.SmoothingMode =
            System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        OnDraw(e.Graphics);
    }
}

在继承类中:

    protected override void OnDraw(Graphics graphics)
    {

        Image toDraw = SelectImageToDraw();

        if (toDraw == null)
        {
            NoImageDraw(graphics);
            return;
        }

        int width = toDraw.Size.Width;
        int height = toDraw.Size.Height;
        Rectangle rect = new Rectangle(0, 0, width, height);

        graphics.DrawImage(toDraw, rect); 
    }

如果用户将鼠标移到控件上,我需要重绘图像。但问题是反对绘制覆盖旧图像。就像我们绘制图层一样。 Winforms 可能无法清除图形,而我的方法会覆盖旧图片。如何解决它,我可能做错了什么。

【问题讨论】:

  • 那么,你想在你的面板控件中绘制一个 png 图像吗?
  • 我有一个透明的 PNG 图像。我需要制作一个“ImageButton” - 控制鼠标进入、离开和单击时重绘图像的内容。所以问题是这个 ImageButton 需要透明并且没有边框。
  • 您想在 Button 上绘制透明图像。按钮后面是form? form 也是透明的吗?
  • 我解决了这个问题。这不是微不足道的。如果我戴上表单用户控件(包含图像)并戴上我的 ImageButton 错误存在。如果我只放置图像并放置 ImageButton 它会正确绘制。我不知道为什么。

标签: c# winforms gdi+


【解决方案1】:

很难理解您的问题是什么——但您是否要在绘制之前清除背景?

使用 Graphics 对象,您可以使用背景颜色调用 Clear 关闭它。如果它后面还有另一个图像,我可以看到你的一些挫败感——但我认为你只需要设置一个透明颜色(并将透明颜色提供给 Clear 方法)。在我看来,这应该清理一切。

http://msdn.microsoft.com/en-us/library/system.drawing.graphics.clear%28v=vs.110%29.aspx

希望能帮助或回答您希望得到解答的问题。

【讨论】:

  • 调用 Clear() 我需要使用颜色作为参数,但我不能使用它,因为我不会填充背景。 Color.Transparent 无法正常工作
  • 你在控件上设置了ColorKey,能用那个Color吗?
猜你喜欢
  • 2020-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-01
  • 2014-03-13
  • 2020-10-24
  • 1970-01-01
  • 2013-11-25
相关资源
最近更新 更多