從MSDN請參見本附註:
Windows窗體控件不支持真正的透明。透明Windows窗體控件的背景 由其父 繪製。
不幸的是,這意味着我們不能通過簡單的方式來做到這一點 - 通過將某種透明圖像控件放在另一個控件上。 WinForms不會這樣做。
我用過的一種方法是在'前景'緩衝區內完成所有的臨時圖形(選區,不完整的圖形等),並使用背景圖像控件的Paint
事件來根據需要繪製臨時對象。
給定一個包含圖像的PaintBox
控件,可以使用Paint
事件根據需要繪製前景緩衝區,提供完全透明度選項。
public partial class Form1 : Form
{
public Bitmap Foreground;
public Form1()
{
InitializeComponent();
// Create foreground buffer same size as picture box
Foreground = new Bitmap(pictureBox1.Width, pictureBox1.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
// Draw a blue ellipse in the foreground buffer for something to see
using (var g = Graphics.FromImage(Foreground))
{
g.Clear(Color.Transparent);
g.DrawEllipse(Pens.Blue, 10, 10, 300, 100);
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(Foreground, 0, 0);
}
}
假設你的圖片框在它的東西,這將繪製一個橢圓藍在它的頂部。
無論何時您想更改重疊的前景圖像,都需要確保PaintBox
控件將被重繪。使用Invalidate
方法告訴Windows控件需要重新繪製。
一些更多的代碼:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
e.Handled = true;
// draw foreground to background
using (var g = Graphics.FromImage(pictureBox1.Image))
g.DrawImage(Foreground, 0, 0);
// clear foreground
using (var g = Graphics.FromImage(Foreground))
g.Clear(Color.Transparent);
}
else if (e.KeyCode == Keys.Space)
{
e.SuppressKeyPress = true;
e.Handled = true;
// a random number source - probably better at form level
var rnd = new Random();
// draw a new random ellipse
using (var g = Graphics.FromImage(Foreground))
{
g.Clear(Color.Transparent);
g.DrawEllipse(Pens.Red, 0, 0, 30 + rnd.Next(500), 30 + rnd.Next(500));
}
// tell Windows to redraw the paintBox to show new foreground image
pictureBox1.Invalidate();
}
}
按Enter
犯PaintBox
前景緩衝器到圖像時,按Space
生成在前臺緩衝區中的隨機新的紅色橢圓。對於各種東西可以使用相同的基本技術,如將圖像粘貼到特定位置(粘貼到前景緩衝區並在其中移動,然後在完成時將前景複製到背景頂部),顯示選擇對象等。
你可以讓你的問題更清楚,,,,你在哪裏要顯示你的繪圖和你在哪裏想得出吧.. – HackerMan
我希望我的矩形面板上繪製的,如MS畫圖,我得到的Mouse_Down事件的起點,然後當我移動鼠標的時候,我的矩形會自動改變它的大小,就像在MS Paint中一樣,然後只有在鼠標被釋放後才能繪製(保存)。 – user3505681