簡體   English   中英

WPF:位圖不顯示

[英]WPF: Bitmap doesn't show

我想創建某種模擬。 周圍將漂浮着許多精靈。 因為我認為將每個幀渲染成組成子畫面的相同圖元的速度會很慢,所以我希望將它們渲染到位圖中一次,然后在每個幀中顯示此子畫面。

但這似乎不起作用,屏幕保持白色。

我的WPF來源很簡單:

<Window x:Class="WPFGraphicsTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="800" Width="1000">
    <Canvas>

    </Canvas>
</Window>

這是我的代碼:

    public partial class MainWindow : Window
    {
        Ellipse e;
        RenderTargetBitmap bmp2;

        public MainWindow()
        {
            InitializeComponent();

            e = new Ellipse();
            e.Width = 40;
            e.Height = 40;
            e.Fill = new SolidColorBrush(Color.FromRgb(0, 0, 200));

            ((Canvas)this.Content).Children.Add(e);
            ((Canvas)this.Content).Measure(new Size(1000, 800));
            ((Canvas)this.Content).Arrange(new Rect(new Size(1000, 800)));

            RenderTargetBitmap bmp2 = new RenderTargetBitmap(40, 40, 96, 96, PixelFormats.Pbgra32);

            bmp2.Render(e);
            ((Canvas)this.Content).Children.Remove(e);
}


        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            drawingContext.DrawImage(bmp2, new Rect(100,100, 40, 40));

        }
}

為什么不起作用?

您可以在畫布上放置一個Image對象,然后使用RenderTargetBitmap更新該圖像。 例如

<Window x:Class="WPFGraphicsTest.MainWindow" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Title="MainWindow" Height="800" Width="1000"> 
    <Canvas> 
      <Image Name="frameImage" />
    </Canvas> 
</Window> 

然后您可以像這樣更新圖像,例如,我只是每100毫秒渲染一個新的橢圓。 當然,您應該比我在這里展示的更好地管理“筆和刷子”,這只是一個澄清建議的示例。

public partial class MainWindow : Window
  {
    DispatcherTimer _timer = new DispatcherTimer();

    RenderTargetBitmap _renderSurface = 
      new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Pbgra32);

    Random _rnd = new Random();

    public MainWindow()
    {
      InitializeComponent();

      _timer = new DispatcherTimer();
      _timer.Interval = TimeSpan.FromMilliseconds(100);
      _timer.Tick += new EventHandler(_timer_Tick);
      _timer.Start();      
    }

    void _timer_Tick(object sender, EventArgs e)
    {
      DrawingVisual visual = new DrawingVisual();
      DrawingContext context = visual.RenderOpen();
      int value = _rnd.Next(40);
      context.DrawEllipse(
        new SolidColorBrush(Colors.Red), 
        new Pen(new SolidColorBrush(Colors.Black), 1), 
        new Point(value, value), value, value);
      context.Close();

      _renderSurface.Render(visual);
      frameImage.Source = _renderSurface;
    }    
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM