如何将禁用的PictureBox用作按钮变灰?

问题描述 投票:0回答:1

我正在将Picturebox控件用作应用程序主仪表板中的按钮。PictureBox当然具有标识Button功能的图像。

如果我使用普通的Button控件,则禁用该按钮后,Button的图像会自动变灰。使用PictureBox不会发生这种情况。

如何使用图片框生成相同的效果

c# winforms graphics picturebox
1个回答
0
投票

由于不想使用按钮,当禁用控件时,该按钮会使您的图像变灰,因此可以使用ColorMatrixPictureBox.BackgroundImage或(图像)更改为灰度。

您在此处看到的GrayScale矩阵使用众所周知的值将Image转换为缩放的灰度表示。您可以找到可能会产生不同结果的同一矩阵对象的其他解释。测试一些或自己进行调整可能很有趣。

灰度过程被实现为Extension method,因为它在其他情况下可能会派上用场。它扩展了Image类,并添加了ToGrayScale()方法(当然,您也可以扩展Bitmap类:您只需要调用Image扩展名,将Bitmap转换为Image即可,也可以根据需要使用其他方法)。


假定您有一个自定义控件,当BackgroundImage更改时,您将为其创建GrayScale表示并将其存储。

然后重写OnEnabledChanged,将BackgroundImage更改为原始版本或其GrayScale版本。通过简单的检查,可以在内部更改BackgroundImage时防止代码生成新的GrayScale图像(这是一种简化的方法,您应该绘制背景,我会尽可能地对其进行更新)。

GrayScale Matrix PictureBox Image

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;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.