【问题标题】:How do I override the paint method of a Winforms control to make it paint to a texture?如何覆盖 Winforms 控件的绘制方法以使其绘制到纹理?
【发布时间】:2012-02-22 17:32:08
【问题描述】:

我正在尝试将 Winforms 与 SharpDX 项目集成,以便在我的 3D 应用程序中使用 Winforms(最终通过 HostElement 使用 WPF)。

我需要创建或配置一个控件或表单,以便我可以:

一个。将其渲染为纹理(我可以将其显示为精灵*)
湾。过滤其输入以在控件未激活时删除鼠标/键盘事件。

我已经尝试子类化 Control 和 Form,以覆盖 OnPaint 和 OnPaintBackground,但这些对子控件没有影响 - 或者就此而言,表单边框(即使他们这样做了,它们本身也不够我是仍然留下一个白色方块,我认为“父母”已被绘制)。

如何停止在屏幕上绘制控件或表单,而只绘制位图?(例如,有没有什么方法可以在绘制树之前覆盖图形?)

*需要这样做(而不是让控件呈现到屏幕上)因为 Winforms 不支持真正的透明度,所以我需要在我的像素着色器中剪辑颜色编码的像素。

(确认一下,我并不是专门指 DirectX 纹理 - 我对(实际上更喜欢)简单的 System.Drawing 位图感到满意)

【问题讨论】:

    标签: c# windows winforms drawing sharpdx


    【解决方案1】:

    这是开始着手的一种方法:

    • 创建一个派生控件类,以便我们可以公开受保护的 InvokePaint
    • 调用我们的自定义方法获取控件的图片
    • 测试表单需要一个图片框和一个Mybutton实例


    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1() { InitializeComponent(); }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                // create image to which we will draw
                var img = new Bitmap(100, 100);
    
                // get a Graphics object via which we will draw to the image
                var g = Graphics.FromImage(img);
    
                // create event args with the graphics object
                var pea = new PaintEventArgs(g, new Rectangle(new Point(0,0), new Size(100,100)));
    
                // call DoPaint method of our inherited object
                btnTarget.DoPaint(pea);
    
                // modify the image with algorithms of your choice...
    
                // display the result in a picture box for testing and proof
                pictureBox.BackgroundImage = img;
            }
        }
    
        public class MyButton : Button
        {
            // wrapping InvokePaint via a public method
            public void DoPaint(PaintEventArgs pea)
            {
                InvokePaint(this, pea);
            }
        }
    }
    

    【讨论】:

    • 显式调用 InvokePaint 效果很好,现在它可以渲染到我的纹理中,谢谢!
    • 您也可以使用“DrawToBitmap”。我认为这将避免从控制中派生的需要。 btnTarget.DrawToBitmap(img, new Rectangle(new Point(0,0), new Size(100,100));
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    相关资源
    最近更新 更多