我正在将Picturebox控件用作应用程序主仪表板中的按钮。
PictureBox当然具有标识Button功能的图像。
如果我使用普通的Button控件,则在禁用该按钮后,Button的图像会自动变灰。
使用PictureBox不会发生这种情况。
如何使用图片框生成相同的效果。
答案 0 :(得分:2)
选项1:CustomControl(图片框)+ ColorMatrix
由于您不想使用按钮,当控件被禁用时,按钮会使您的图像变灰,因此您可以使用ColorMatrix来更改PictureBox.BackgroundImage
或(图像)灰度。
您在此处看到的GrayScale矩阵使用众所周知的值将Image转换为缩放的灰度表示。您可以找到同一矩阵对象的其他解释,这些解释可能会产生不同的结果。
自己测试一些或对其进行调整可能很有趣。
GrayScale过程被实现为Extension method,因为它在其他情况下可能会派上用场。
它扩展了Image类,并添加了一个ToGrayScale()
方法(当然,您也可以扩展Bitmap类:您只需要调用Image扩展名,将Bitmap转换为Image即可,也可以根据需要使用其他方法)。
假设您有一个自定义控件,则当BackgroundImage更改时,您将为其创建GrayScale表示并将其存储。
然后覆盖OnEnabledChanged
,将BackgroundImage更改为原始版本或其GrayScale版本。进行简单的检查可以防止在内部更改BackgroundImage时代码生成新的GrayScale图像(这是一种简化的方法,您应该绘制背景。我会尽可能地对其进行更新)。
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
[DesignerCategory("Code")]
public class ButtonPicture : PictureBox
{
private Image m_sourceImage = null;
private Image m_grayImage = null;
public ButtonPicture() { }
protected override void OnEnabledChanged(EventArgs e) {
base.OnEnabledChanged(e);
this.BackgroundImage = this.Enabled ? m_sourceImage : m_grayImage;
}
protected override void OnBackgroundImageChanged(EventArgs e) {
base.OnBackgroundImageChanged(e);
if (this.BackgroundImage == m_sourceImage ||
this.BackgroundImage == m_grayImage) return;
m_sourceImage = this.BackgroundImage;
m_grayImage = m_sourceImage.ToGrayScale();
}
protected override void Dispose(bool disposing) {
if (disposing) {
m_grayImage.Dispose();
}
base.Dispose(disposing);
}
}
扩展方法:
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public static class ImageExtensions
{
static ColorMatrix grayMatrix = new ColorMatrix(new float[][]
{
new float[] { .2126f, .2126f, .2126f, 0, 0 },
new float[] { .7152f, .7152f, .7152f, 0, 0 },
new float[] { .0722f, .0722f, .0722f, 0, 0 },
new float[] { 0, 0, 0, 1, 0 },
new float[] { 0, 0, 0, 0, 1 }
});
public static Bitmap ToGrayScale(this Image source) {
var grayImage = new Bitmap(source.Width, source.Height, source.PixelFormat);
grayImage.SetResolution(source.HorizontalResolution, source.VerticalResolution);
using (var g = Graphics.FromImage(grayImage))
using (var attributes = new ImageAttributes()) {
attributes.SetColorMatrix(grayMatrix);
g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height),
0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes);
return grayImage;
}
}
}
选项2:ControlPaint + PictureBox.Paint事件(标记)
您可以使用ControlPaint.DrawImageDisabled()方法绘制禁用位图。
PictureBox.Paint
事件并将e.Graphics
对象传递给方法。Image
参数可以是PictureBox.Image
属性值的副本。►比较左侧的图像,使用ColorMatrix禁用了 ;右侧的图像使用ControlPaint方法禁用了 :
private void buttonPicture_Paint(object sender, PaintEventArgs e)
{
var pict = sender as PictureBox;
if (pict != null && (!pict.Enabled)) {
using (var img = new Bitmap(pict.Image, pict.ClientSize)) {
ControlPaint.DrawImageDisabled(e.Graphics, img, 0, 0, pict.BackColor);
}
}
}