📄 form1.cs
字号:
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace MobileDevelopersHandbook.AlphaBlendExample
{
public partial class Form1 : Form
{
protected Bitmap backBuffer;
protected Image displayImage;
byte transparencyValue = 0;
Timer blendTimer;
public Form1()
{
InitializeComponent();
// Load the image to use with the AlphaBlend API.
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
displayImage = new Bitmap(path + @"\Microsoft_Windows_Mobile_logo.bmp");
blendTimer = new Timer();
blendTimer.Interval = 50;
blendTimer.Tick += new EventHandler(blendTimer_Tick);
blendTimer.Enabled = true;
}
void blendTimer_Tick(object sender, EventArgs e)
{
transparencyValue += 10;
if (transparencyValue == 250)
{
transparencyValue = 255; // opaque
blendTimer.Enabled = false; // stop the tmer
}
// Force a repaint
this.Refresh();
}
protected override void OnPaintBackground(PaintEventArgs e)
{
// Make this a no-op, to avoid flicker
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (backBuffer != null)
{
// We need a Graphics object on the buffer to get an HDC
using (Graphics gxBuffer = Graphics.FromImage(backBuffer))
{
// Since we nop'd OnPaintBackground, take care of it here
gxBuffer.Clear(this.BackColor);
// AlphaBlend takes two HDC's - one source and one destination. Here's the source.
using (Graphics gxSrc = Graphics.FromImage(displayImage))
{
IntPtr hdcDst = gxBuffer.GetHdc();
IntPtr hdcSrc = gxSrc.GetHdc();
BlendFunction blendFunction = new BlendFunction();
blendFunction.BlendOp = (byte)BlendOperation.AC_SRC_OVER; // Only supported blend operation
blendFunction.BlendFlags = (byte)BlendFlags.Zero; // Documentation says put 0 here
blendFunction.SourceConstantAlpha = transparencyValue; // Constant alpha factor
blendFunction.AlphaFormat = (byte)0; // Don't look for per pixel alpha
int left = this.Width / 2 - (displayImage.Width / 2); // Get x co-or based on bitmap width
int top = 100; // y co-or
PlatformAPIs.AlphaBlend(hdcDst, left, top,
displayImage.Width, displayImage.Height,
hdcSrc, 0, 0,
displayImage.Width, displayImage.Height,
blendFunction);
gxBuffer.ReleaseHdc(hdcDst); // Required cleanup to GetHdc()
gxSrc.ReleaseHdc(hdcSrc); // Required cleanup to GetHdc()
}
}
// Put the final composed image on screen.
e.Graphics.DrawImage(backBuffer, 0, 0);
}
else
e.Graphics.Clear(this.BackColor);
}
private void Form1_Resize(object sender, EventArgs e)
{
if (backBuffer != null)
{
// dispose of the original one
backBuffer.Dispose();
}
// Create a new backbuffer of the correct size
backBuffer = new Bitmap(this.ClientSize.Width, this.ClientSize.Height,
System.Drawing.Imaging.PixelFormat.Format32bppRgb);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -