Direct2D,WPF D3D10 图像在调整大小时模糊

Posted

技术标签:

【中文标题】Direct2D,WPF D3D10 图像在调整大小时模糊【英文标题】:Direct2D, WPF D3D10 image blurs on resizing 【发布时间】:2021-03-17 19:33:30 【问题描述】:

我正在开发一个 WPF 应用程序,它使用 DirectX 为我的应用程序绘制背景和边框。我使用了这里的代码:Using Direct2D with WPF

代码工作正常,但是当我绘制一个矩形并且没有填充矩形时,在调整大小时它会变得模糊。 这是问题的屏幕截图。

窗口周围的红色边框是我绘制的矩形。我对代码所做的唯一更改如下:

protected override void OnRender() 
  // Calculate our actual frame rate
  this.frameCount++;
  if (DateTime.UtcNow.Subtract(this.time).TotalSeconds >= 1) 
    this.fps = this.frameCount;
    this.frameCount = 0;
    this.time = DateTime.UtcNow;
  

  // This is what we're going to draw. We'll animate the width of the
  // elipse over a span of five seconds (ElapsedTime / 5).
  this.widthRatio += this.ElapsedTime / 5;
  if (this.widthRatio > 1) // Reset
  
    this.widthRatio = 0;
  

  var size = this.RenderTarget.Size;
  float width = (float)((size.Width / 3.0) * this.widthRatio);
  var ellipse = new D2D.Ellipse(new D2D.Point2F(size.Width / 2.0f, size.Height / 2.0f), width, size.Height / 3.0f);
  var rect = new D2D.RectF();
  rect.Height = size.Height;
  rect.Width = size.Width;
  rect.Top = 0;
  rect.Left = 0;
  // This draws the ellipse in red on a semi-transparent blue background
  this.RenderTarget.BeginDraw();
  this.RenderTarget.Clear(new D2D.ColorF(0, 0, 0, 1f));
  this.RenderTarget.FillEllipse(ellipse, this.redBrush);
  // Draw a little FPS in the top left corner
  string text = string.Format("FPS 0", this.fps);
  this.RenderTarget.DrawRectangle(rect, redBrush, 10f);
  this.RenderTarget.DrawText(text, this.textFormat, new D2D.RectF(10, 10, 100, 20), this.whiteBrush);

  // All done!
  this.RenderTarget.EndDraw();

我认为问题是由于 WPF 在调整大小时无法调整 D3D10 图像的大小。有什么办法可以解决这个问题。

【问题讨论】:

【参考方案1】:

最后我找到了一个很简单的答案。 Direct2D 控件只不过是一个普通的图像控件。问题是图像无法及时调整大小。我给定的代码使用 DispatcherTimer 调整了图像的大小,这会导致延迟。所以我将ResizeTimerTick() 函数中的代码复制到了一个新的公共函数中,并在我的窗口上的OnSizeChanged() 事件中调用了该函数。这是我使用的代码。

public void onResize() 
    if (this.Scene != null) 
        // Check we don't resize too small
        int width = Math.Max(1, (int) this.ActualWidth);
        int height = Math.Max(1, (int) this.ActualHeight);
        this.Scene.Resize(width, height);

        this.imageSource.Lock();
        this.imageSource.SetBackBuffer(this.Scene.Texture);
        this.imageSource.Unlock();

        this.Scene.Render();
    

在 MainWindow.cs 中:

private void Window_SizeChanged(object sender, SizeChangedEventArgs e) 
    d2DControl.onResize();

注意:此方法会消耗更多内存(大约 74 MB)

【讨论】:

以上是关于Direct2D,WPF D3D10 图像在调整大小时模糊的主要内容,如果未能解决你的问题,请参考以下文章

Direct2D 第5篇 绘制图像

神秘的Direct2D内存泄漏与渐变

Direct2D开发:向 MFC 项目添加 Direct2D 对象

WPF/C#单击图像缩略图->显示该图像大[关闭]

WPF C#实现了一个调整大小的抓握

WPF的Canvas如何在程序运行时动态地调整布局?