在C#中将Int转换为Color用于Silverlight的WriteableBitmap

时间:2009-07-15 20:34:02

标签: c# silverlight

在Silverlight 3中,现在有一个WriteableBitmap,它提供了get / put像素功能。这可以这样做:

// setting a pixel example
WriteableBitmap bitmap = new WriteableBitmap(400, 200);
Color c = Colors.Purple;
bitmap.Pixels[0] = c.A << 24 | c.R << 16 | c.G << 8 | c.B;

基本上,设置Pixel涉及设置其颜色,并通过将alpha,red,blue,green值按位移位为整数来实现。

我的问题是,你如何将整数转回颜色?在这个例子中缺少的是什么:

// getting a pixel example
int colorAsInt = bitmap.Pixels[0];
Color c;
// TODO:: fill in the color c from the integer ??

感谢您提供的任何帮助,我只是没有意识到我的位移,我相信其他人会在某些时候陷入这个障碍。

7 个答案:

答案 0 :(得分:7)

使用反射器我发现在标准.net调用中如何解析R,G,B(在Silverlight中不可用):

System.Drawing.ColorTranslator.FromWin32()

从那我开始猜测如何获得alpha通道,这就完成了工作:

Color c2 = Color.FromArgb((byte)((colorAsInt >> 0x18) & 0xff), 
                          (byte)((colorAsInt >> 0x10) & 0xff), 
                          (byte)((colorAsInt >> 8) & 0xff), 
                          (byte)(colorAsInt & 0xff));

答案 1 :(得分:4)

您可以使用BitConverter.GetBytes()将int转换为一个字节数组,该数组可以使用Silverlight具有的FromArgb的重载...

Color.FromArgb(BitConverter.GetBytes(intVal)); 

// or if that doesn't work
var bytes = BitConverter.GetBytes(intVal);
Color.FromArgb(bytes[3], bytes[2], bytes[1], bytes[0]); 

答案 2 :(得分:2)

未涵盖的是WriteableBitmap使用 预乘 ARGB32,因此如果您有半透明像素,则R,G和B值将从0到Alpha值。

要获得Color值,您需要执行相反的操作并将其缩放回0到255.如下所示。

r = (byte)(r * (255d / alpha))

答案 3 :(得分:0)

您可能正在寻找ColorTranslator class,但我不确定它是否适用于SilverLight或您需要的内容。尽管如此,这绝对是一个很好的人。

编辑:Here was one person's suggestion(使用反射复制课程,所以从那时起你就有了一个人们已经熟悉的转换器。)

答案 4 :(得分:0)

public static Color ToColor(this uint argb)
{
    return Color.FromArgb((byte)((argb & -16777216) >> 0x18),
                          (byte)((argb & 0xff0000) >> 0x10),
                          (byte)((argb & 0xff00) >> 8),
                          (byte)(argb & 0xff));
}

并使用:

Color c = colorAsInt.ToColor()

答案 5 :(得分:0)

我认为这样的事情应该有效:

public byte[] GetPixelBytes(WriteableBitmap bitmap)
{
   int[] pixels = bitmap.Pixels;
   int length = pixels.Length * 4;
   byte[] result = new byte[length]; // ARGB
   Buffer.BlockCopy(pixels, 0, result, 0, length);
   return result;
}

获得字节后,使用任何各种Color API都可以轻松获取颜色。

答案 6 :(得分:-1)

Color.FromArgb(intVal)