简体   繁体   English

绘制图像,然后将该图像渲染到具有透明背景的窗口?

[英]Draw to an image then render that image to a window with a transparent background?

WinForms Project WinForms项目

Im trying to draw to an image then draw that to a window that is external to my application using: 我试图绘制图像,然后使用以下方法将其绘制到应用程序外部的窗口:

using(var g = Graphics.FromHandle(handle))
g.DrawImage(myImage);

to reduce flickering behavior when drawing. 以减少绘图时的闪烁行为。

I know that I can use the BufferedGraphics class, but it had a black background so I tried to draw a transparent image to it first and then draw on top of that but it still had a black background when rendering it. 我知道我可以使用BufferedGraphics类,但是它具有黑色背景,因此我尝试先在其上绘制透明图像,然后再在其上绘制,但是渲染时它仍然具有黑色背景。

Is there any way to use BufferedGraphics or a way of drawing once to memory so it can be drawn as a whole image at once (to reduce flickering) to screen with a transparent background? 有什么方法可以使用BufferedGraphics或一次在内存中绘制一次,以便可以一次将其绘制为整个图像(以减少闪烁)以显示具有透明背景的屏幕吗?

i assume that you are using a timer and drawing the image each time the tick event fires and that's the reason of the flickering 我假设您正在使用计时器并在每次滴答事件触发时绘制图像,这就是闪烁的原因

So, first create a winform, i am putting the backColor to red so you can see the transparency of the background better 因此,首先创建一个winform,我将backColor设置为红色,以便更好地查看背景的透明度。

在此处输入图片说明

Add one timer and turn on the tick event Then choose an image with transparency in png, one like this: 添加一个计时器并打开刻度事件,然后选择一个具有png透明度的图像,如下所示:

在此处输入图片说明

Put it in the directory where you start your application from 将其放在您从中启动应用程序的目录中

在此处输入图片说明

Finally this is the code, it's fully functional, i tested already :v 最后这是代码,它功能齐全,我已经测试过了:v

using System;
using System.Collections.Generic;
using System.ComponentModel;
System.Data;
System.Drawing;
System.IO;
System.Linq;
System.Text;
System.Threading.Tasks;
System.Windows.Forms;
namespace so
{
public partial class Form1 : Form
{
    Image image;
    public Form1()
    {
        image = Image.FromFile("imagen.png");
        InitializeComponent();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        Graphics gr = this.CreateGraphics();
        BufferedGraphicsContext bgc = BufferedGraphicsManager.Current;
        BufferedGraphics bg = bgc.Allocate(gr,this.ClientRectangle);
        //before drawing the image clean the background with the current form's Backcolor
        bg.Graphics.Clear(this.BackColor);
        //use any overload of drawImage, the best for your project
        bg.Graphics.DrawImage(image,0,0);
        bg.Render(gr);
    }
}
}

Maybe i didn't understand correctly your answer, but this will avoid the flickering and show one image with transparent background without any problem :) 也许我不正确理解您的答案,但这可以避免闪烁,并以透明背景显示一张图像而没有任何问题:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM