使用 SharpDX.Direct2D1 在特定元素上呈现

using SharpDX.Direct2D1 to render on specific element

提问人:Par Partuk 提问时间:8/30/2023 最后编辑:Simon MourierPar Partuk 更新时间:8/31/2023 访问量:36

问:

我正在WPF应用程序中使用SharpDX渲染缓冲区。我已经创建了一个,我正在为它绘制一个 SharpDX 位图。一切正常,但我面临一个问题:缓冲区在整个窗口上呈现,而我需要将其呈现到窗口中的特定元素上。如何在 WPF 中使用 SharpDX 实现对特定元素的渲染?WindowRenderTarget

这是我用于渲染的代码:

 private void InitializeDirect2D()
        {
            var hwnd = ((HwndSource)PresentationSource.FromVisual(image)).Handle;
            var factory = new SharpDX.Direct2D1.Factory1(FactoryType.MultiThreaded);
            var renderProps = new HwndRenderTargetProperties
            {
                Hwnd = hwnd,
                PixelSize = new Size2((int)ActualWidth, (int)ActualHeight),
                PresentOptions = PresentOptions.Immediately
            };

            var renderTargetProperties = new RenderTargetProperties
            {
                DpiX = 96,
                DpiY = 96,
                MinLevel = FeatureLevel.Level_DEFAULT,
                Type = RenderTargetType.Hardware,
                Usage = RenderTargetUsage.None
            };
            properties = new BitmapProperties(new SharpDX.Direct2D1.PixelFormat(Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied));
            renderTarget = new WindowRenderTarget(factory, renderTargetProperties, renderProps);

        }
        public void DrawBitmap()
        {
            int width = frame.width;
            int height = frame.height;
            int stride = width * 4;
            IntPtr buffer = (IntPtr)frame.data[0];
            using (var stream = new DataStream(buffer, stride * height, true, false))
            {
                var bitmap = new SharpDX.Direct2D1.Bitmap(renderTarget, new Size2(width, height), stream, stride, properties);
                renderTarget.BeginDraw();
                RawColor4 clearColor = new RawColor4(255, 255, 255, 255);
                renderTarget.Clear(clearColor);
                renderTarget.DrawBitmap(bitmap, 1.0f, SharpDX.Direct2D1.BitmapInterpolationMode.Linear);
                renderTarget.EndDraw();
                bitmap.Dispose();
            }
        }

上面的代码有效,但它在整个窗口中呈现缓冲区。有没有办法将窗口内的特定元素(例如,a 或控件)作为目标,以便呈现仅限于该元素?CanvasImage

谢谢! ``

WPF Direct2D SharpDX

评论

0赞 Simon Mourier 8/31/2023
在 HWND 上创建 HWND 呈现目标 (learn.microsoft.com/en-us/windows/win32/api/d2d1/...) 后,整个 HWND 图面就是你的了。你可以改用 D3DImage learn.microsoft.com/en-us/dotnet/api/...,但这需要更改体系结构。WPF(仍然)基于 DirectX9,不能很好地与更现代的技术配合使用。一种解决方案是迁移到 WinUI3 并改用 SwapChainPanel(这是窗口内的元素,而不是*整个窗口)。显然,这取决于您的上下文,这可能是一项艰巨的任务。

答: 暂无答案