首页 > 解决方案 > 如何将元文件的颜色设置为特定值?

问题描述

我需要将元文件中所有可用对象的颜色更改为特定颜色。但是,当前提供的仅用于平移/缩放/旋转颜色。例如,我需要将所有可用对象的颜色设置为绿色。

下面目前讨论的是只是相对地改变颜色,而不是绝对地改变颜色:

https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/recoloring-images

如何在 C# 中更改 EMF+ 图像的颜色

这段代码可以做的只是将所有颜色转换为白色。但我需要将所有颜色设置为例如绿色、深红色等。有没有办法做到这一点?

ImageAttributes GetAttr()
{
    /* Get image attributes to translate to white */
    float[][] colorMatrixElements = {
            new float[] {1,  0,  0,  0, 0}, // no red scaling
            new float[] {0,  1,  0,  0, 0}, // no green scaling
            new float[] {0,  0,  1,  0, 0}, // no blue scaling
            new float[] {0,  0,  0,  1, 0}, // no alpha scaling
            new float[] {1, 1, 1, 1, 1}}; // four translations of 1.0
    ImageAttributes imageAttributes = new ImageAttributes();
    imageAttributes.SetColorMatrix(new ColorMatrix(colorMatrixElements));
    return imageAttributes;
}

void test()
{
    var fname = Path.GetTempFileName();
    var frame = new Rectangle(0, 0, 640, 480);
    using (var img = new Metafile(fname, CreateGraphics().GetHdc(), frame, MetafileFrameUnit.Point))
    {
        using (var g = Graphics.FromImage(img))
        {
            var arrow = new Metafile("arrow.emf");
            g.DrawImage(arrow, new Rectangle(150, 400, 75, 50),
                0, 0, arrow.Width, arrow.Height, GraphicsUnit.Pixel, GetAttr());
        }
    }
}

标签: c#colorsgdi+metafile

解决方案


推荐阅读