1

我想将线性渐变的不透明度应用于图像,但我所能得到的只是绘制在图像顶​​部的渐变。

在此处输入图像描述

这个 stackoverflow帖子之后,我创建了一个继承自 PictureBox 的用户控件,并覆盖了 OnPaint 方法

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        LinearGradientBrush linearGradientBrush = new LinearGradientBrush(
            this.ClientRectangle,
            Color.FromArgb(255, Color.White),
            Color.FromArgb(0, Color.White),
            0f);
        e.Graphics.FillRectangle(linearGradientBrush, this.ClientRectangle);
    }

但是,这只是在图像顶部绘制线性渐变。

如何将线性渐变的不透明度应用于图像

我在 XAML () 中找到了示例,但在 winforms 中没有。

4

1 回答 1

3

不必使用用户控件并覆盖OnPaint事件。只需从空白图像创建图形对象并进行图像处理并将图像分配给PicturePox.

首先将 linearGradientBrush 绘制到背景,然后在其上绘制图像。始终注意图像操作的顺序。

FileInfo inputImageFile = new FileInfo(@"C:\Temp\TheSimpsons.png");
Bitmap inputImage = (Bitmap)Bitmap.FromFile(inputImageFile.FullName);

// create blank bitmap with same size
Bitmap combinedImage = new Bitmap(inputImage.Width, inputImage.Height);

// create graphics object on new blank bitmap
Graphics g = Graphics.FromImage(combinedImage);

// also use the same size for the gradient brush and for the FillRectangle function
LinearGradientBrush linearGradientBrush = new LinearGradientBrush(
    new Rectangle(0,0,combinedImage.Width, combinedImage.Height),
    Color.FromArgb(255, Color.White), //Color.White,
    Color.FromArgb(0, Color.White), // Color.Transparent,
    0f);
g.FillRectangle(linearGradientBrush, 0, 0, combinedImage.Width, combinedImage.Height);

g.DrawImage(inputImage, 0,0);

previewPictureBox.Image = combinedImage;

结果

结果以黑色作为表单背景颜色,示例图像具有透明度。

编辑:我可能误解了意图,或者没有找到像 WPF 那样的简单方法,但这并没有那么困难。

FileInfo inputImageFile = new FileInfo(@"C:\Temp\TheSimpsons.png");
Bitmap inputImage = (Bitmap)Bitmap.FromFile(inputImageFile.FullName);

// create blank bitmap
Bitmap adjImage = new Bitmap(inputImage.Width, inputImage.Height);

// create graphics object on new blank bitmap
Graphics g = Graphics.FromImage(adjImage);

LinearGradientBrush linearGradientBrush = new LinearGradientBrush(
    new Rectangle(0, 0, adjImage.Width, adjImage.Height),
    Color.White,
    Color.Transparent,
    0f);

Rectangle rect = new Rectangle(0, 0, adjImage.Width, adjImage.Height);
g.FillRectangle(linearGradientBrush, rect);

int x;
int y;
for (x = 0; x < adjImage.Width; ++x)
{
    for (y = 0; y < adjImage.Height; ++y)
    {
        Color inputPixelColor = inputImage.GetPixel(x, y);
        Color adjPixelColor = adjImage.GetPixel(x, y);
        Color newColor = Color.FromArgb(adjPixelColor.A, inputPixelColor.R, inputPixelColor.G, inputPixelColor.B);
        adjImage.SetPixel(x, y, newColor);
    }
}
previewPictureBox.Image = adjImage;

在此处输入图像描述

于 2016-11-21T11:55:13.600 回答