gpt4 book ai didi

c# - 用于检索颜色的 Canvas 背景

转载 作者:太空宇宙 更新时间:2023-11-03 16:54:09 25 4
gpt4 key购买 nike

我有一个背景设置为 lineargradientbrush 的 Canvas ....然后如何从该背景中提取特定鼠标点 (x,y) 处的颜色?

我可以用 BitmappedImage 很好地做到这一点...因为它处理像素,但不确定 Canvas ...

非常感谢,

你。

最佳答案

Ray Burns 发布的代码对我不起作用,但它确实引导我走上了正确的道路。经过一些研究和实验后,我发现问题出在 bitmap.Render(...) 实现及其使用的 Viewbox 上。

注意:我使用的是 .Net 3.5 和 WPF,所以他的代码可能适用于其他版本的 .Net。

这里特意留下注释以帮助解释代码。

如您所见,Viewbox 需要根据源视觉高度和宽度进行标准化。

DrawingVisual 需要在渲染之前使用 DrawingContext 绘制。

在 RenderTargetBitmap 方法中,我尝试了 PixelFormats.Default 和 PixelFormats.Pbgra32。我的测试结果与他们两个相同。

这是代码。

    public static Color GetPixelColor(Visual visual, Point pt)
{
Point ptDpi = getScreenDPI(visual);

Size srcSize = VisualTreeHelper.GetDescendantBounds(visual).Size;

//Viewbox uses values between 0 & 1 so normalize the Rect with respect to the visual's Height & Width
Rect percentSrcRec = new Rect(pt.X / srcSize.Width, pt.Y / srcSize.Height,
1 / srcSize.Width, 1 / srcSize.Height);

//var bmpOut = new RenderTargetBitmap(1, 1, 96d, 96d, PixelFormats.Pbgra32); //assumes 96 dpi
var bmpOut = new RenderTargetBitmap((int)(ptDpi.X / 96d),
(int)(ptDpi.Y / 96d),
ptDpi.X, ptDpi.Y, PixelFormats.Default); //generalized for monitors with different dpi

DrawingVisual dv = new DrawingVisual();
using (DrawingContext dc = dv.RenderOpen())
{
dc.DrawRectangle(new VisualBrush { Visual = visual, Viewbox = percentSrcRec },
null, //no Pen
new Rect(0, 0, 1d, 1d) );
}
bmpOut.Render(dv);

var bytes = new byte[4];
int iStride = 4; // = 4 * bmpOut.Width (for 32 bit graphics with 4 bytes per pixel -- 4 * 8 bits per byte = 32)
bmpOut.CopyPixels(bytes, iStride, 0);

return Color.FromArgb(bytes[0], bytes[1], bytes[2], bytes[3]);
}

如果您对 getScreenDPI() 函数感兴趣,代码是:

    public static Point getScreenDPI(Visual v)
{
//System.Windows.SystemParameters
PresentationSource source = PresentationSource.FromVisual( v );
Point ptDpi;
if (source != null)
{
ptDpi = new Point( 96.0 * source.CompositionTarget.TransformToDevice.M11,
96.0 * source.CompositionTarget.TransformToDevice.M22 );
}
else
ptDpi = new Point(96d, 96d); //default value.

return ptDpi;
}

而且用法和Ray的差不多。我在这里显示它是为了在 Canvas 上按下 MouseDown。

    private void cvsTest_MouseDown(object sender, MouseButtonEventArgs e)
{
Point ptClicked = e.GetPosition(cvsTest);

if (e.LeftButton.Equals(MouseButtonState.Pressed))
{
Color pxlColor = ImagingTools.GetPixelColor(cvsTest, ptClicked);
MessageBox.Show("Color String = " + pxlColor.ToString());
}
}

仅供引用,ImagingTools 是我保存与成像相关的静态方法的类。

关于c# - 用于检索颜色的 Canvas 背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2835466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com