65.9K
CodeProject 正在变化。 阅读更多。
Home

图像反射

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.76/5 (22投票s)

2009年6月8日

公共领域

1分钟阅读

viewsIcon

60333

downloadIcon

2421

学习如何从选定的图像生成反射。

GDI__Glass_Reflection

引言

这段源代码将教你如何在 C#.NET 中创建简单的 GDI+ 玻璃反射效果。   

代码  

请确保包含这些命名空间

System.Drawing; 
System.Drawing.Drawing2D; 
System.Drawing.Imaging;

这是 DrawImage 代码。它从 pictureBox1 获取图像,然后创建反射。

private static Image DrawReflection(Image img,Color toBG) // img is the original image.
{
    //This is the static function that generates the reflection...
    int height = img.Height + 100; //Added height from the original height of the image.
    Bitmap bmp = new Bitmap(img.Width, height, PixelFormat.Format64bppPArgb); //A new 
								//bitmap.
    //The Brush that generates the fading effect to a specific color of your background.
    Brush brsh = new LinearGradientBrush(new Rectangle(0, 0, img.Width + 10, 
      height), Color.Transparent, toBG, LinearGradientMode.Vertical);
    bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution); //Sets the new 
							//bitmap's resolution.
    using(Graphics grfx = Graphics.FromImage(bmp)) //A graphics to be generated 
			//from an image (here, the new Bitmap we've created (BMP)).
     {
        Bitmap bm = (Bitmap)img; //Generates a bitmap from the original image (img).
        grfx.DrawImage(bm, 0, 0, img.Width, img.Height); //Draws the generated 
					//bitmap (bm) to the new bitmap (bmp).
        Bitmap bm1 = (Bitmap)img; 	//Generates a bitmap again 
				//from the original image (img).
        bm1.RotateFlip(RotateFlipType.Rotate180FlipX); //Flips and rotates the 
						//image (bm1).
        grfx.DrawImage(bm1, 0, img.Height); 	//Draws (bm1) below (bm) so it serves 
					//as the reflection image.
        Rectangle rt = new Rectangle(0, img.Height, img.Width, 100); //A new rectangle 
						//to paint our gradient effect.
        grfx.FillRectangle(brsh, rt); //Brushes the gradient on (rt).
     }
    return bmp; //Returns the (bmp) with the generated image.
}

创建此函数后,使用它通过单击事件或其他事件更改 picturebox 的图像。

private void controlname_click(Object sender, EventArgs e)
{
pictureBox1.Image = DrawReflection(pictureBox1.Image, Color.Black);
}

这段代码将当前的 pictureBox1 的图像更改为 DrawReflection 生成的图像。 

它是如何工作的?

如果图像没有使用渐变绘制,这就是结果。

GlassReflection/Image_without_gradient.png

渐变解释

GlassReflection/Image.png

原始图像下方的翻转图像具有渐变效果,因为我们在其上绘制了渐变。起始颜色是 Transparent(透明)。我们可以看到它下方的图像。随着向下移动,它变为黑色,这是表单的颜色,因此图像的下部与背景颜色融合,从而产生渐变效果。

此解决方案解决了什么问题?

我制作此解决方案是为了让初学者更好地理解 C#.NET 中的图像反射。它是在主窗体类中创建的。 

这对某人有什么帮助?

这有助于更好地理解 System.Drawing 类和函数的使用。

历史

  • 2009/03/06 - 初始发布(此源代码)
  • 2024/01/09 - 发布到公共领域
© . All rights reserved.