繁体   English   中英

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

[英]Converting Int to Color in C# for Silverlight's WriteableBitmap

在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 ??

感谢您提供的任何帮助,我只是不知道我的位移,我相信其他人会在某些时候遇到这个障碍。

使用反射器我发现如何在标准.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));

您可以使用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]); 

没有涉及的是WriteableBitmap使用预乘 ARGB32,因此如果你有一个半透明像素,R,G和B值将从0缩放到Alpha值。

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

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

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

编辑: 这是一个人的建议 (使用反射复制课程,所以从那时起你有一个人们已经熟悉的转换器)。

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()

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

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轻松获取颜色。

Color.FromArgb(intVal)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM