如何在 SharpDX 上获取 Direct2D 位图的像素颜色
How to get pixel color of Direct2D bitmap on SharpDX
我使用 SharpDX,但我不明白如何在位图中获取像素颜色。我找到了 CopySubresourceRegion 方法,但它适用于 Direct3D。
我有个奇怪的想法:
我可以创建 RenderForm 并在窗体上绘制位图。然后得到表格的图形。然后通过 "new Bitmap(width, height, graphics)" 创建位图。然后从新位图中获取像素颜色;
如果您的目标是 Direct2D 1.1(或更高版本),那么您可以在创建位图时使用位图上的 ID2D1Bitmap1::Map method. This will require that you set D2D1_BITMAP_OPTIONS_CPU_READ and D2D1_BITMAP_OPTIONS_CANNOT_DRAW flags。
我编写了获取像素颜色的特殊函数。这解决了我的问题;)
C# - SharpDX
Color4 GetPixel(Bitmap image, int x, int y, RenderTarget renderTarget) {
var deviceContext2d = renderTarget.QueryInterface<DeviceContext>();
var bitmapProperties = new BitmapProperties1();
bitmapProperties.BitmapOptions = BitmapOptions.CannotDraw | BitmapOptions.CpuRead;
bitmapProperties.PixelFormat = image.PixelFormat;
var bitmap1 = new Bitmap1(deviceContext2d, new Size2((int)image.Size.Width, (int)image.Size.Height), bitmapProperties);
bitmap1.CopyFromBitmap(image);
var map = bitmap1.Map(MapOptions.Read);
var size = (int)image.Size.Width * (int)image.Size.Height * 4;
byte[] bytes = new byte[size];
Marshal.Copy(map.DataPointer, bytes, 0, size);
bitmap1.Unmap();
bitmap1.Dispose();
deviceContext2d.Dispose();
var position = (y * (int)image.Size.Width + x) * 4;
return new Color4(bytes[position], bytes[position + 1], bytes[position + 2], bytes[position + 3]);
}
我使用 SharpDX,但我不明白如何在位图中获取像素颜色。我找到了 CopySubresourceRegion 方法,但它适用于 Direct3D。 我有个奇怪的想法:
我可以创建 RenderForm 并在窗体上绘制位图。然后得到表格的图形。然后通过 "new Bitmap(width, height, graphics)" 创建位图。然后从新位图中获取像素颜色;
如果您的目标是 Direct2D 1.1(或更高版本),那么您可以在创建位图时使用位图上的 ID2D1Bitmap1::Map method. This will require that you set D2D1_BITMAP_OPTIONS_CPU_READ and D2D1_BITMAP_OPTIONS_CANNOT_DRAW flags。
我编写了获取像素颜色的特殊函数。这解决了我的问题;) C# - SharpDX
Color4 GetPixel(Bitmap image, int x, int y, RenderTarget renderTarget) {
var deviceContext2d = renderTarget.QueryInterface<DeviceContext>();
var bitmapProperties = new BitmapProperties1();
bitmapProperties.BitmapOptions = BitmapOptions.CannotDraw | BitmapOptions.CpuRead;
bitmapProperties.PixelFormat = image.PixelFormat;
var bitmap1 = new Bitmap1(deviceContext2d, new Size2((int)image.Size.Width, (int)image.Size.Height), bitmapProperties);
bitmap1.CopyFromBitmap(image);
var map = bitmap1.Map(MapOptions.Read);
var size = (int)image.Size.Width * (int)image.Size.Height * 4;
byte[] bytes = new byte[size];
Marshal.Copy(map.DataPointer, bytes, 0, size);
bitmap1.Unmap();
bitmap1.Dispose();
deviceContext2d.Dispose();
var position = (y * (int)image.Size.Width + x) * 4;
return new Color4(bytes[position], bytes[position + 1], bytes[position + 2], bytes[position + 3]);
}