3

我正在尝试PictureBox从我插入的相机上绘制图像WindowsFormsHost。代码很简单如下:

<Window x:Class="videoTEst.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="583" Width="1132"
    xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms">
<StackPanel Background="LightBlue" Height="513" Width="1077">
    <StackPanel HorizontalAlignment="Center" Width="450" Orientation="Horizontal">
        <Button Name="ButtonOpen" Content="Load" Click="ButtonOpen_OnClick" />
        <Button Name="ButtonLoadImage" Content="Load image" Click="ButtonLoadImage_OnClick" />
        </StackPanel>
    <StackPanel Orientation="Horizontal">
        <WindowsFormsHost Name="WinFormsHost" Height="440" Width="690" HorizontalAlignment="Left">
                <wf:PictureBox x:Name="PictureBoxvideo" SizeMode="Normal" Paint="PictureBoxvideo_Paint"></wf:PictureBox>
        </WindowsFormsHost>
        <ListBox Name="ListBoxLog" />
    </StackPanel>
</StackPanel>

我像这样从相机中绘画:

 private void asyncVideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
    {
        Image temp = PictureBoxvideo.Image;
        Bitmap bitmap = eventArgs.Frame;
        PictureBoxvideo.Image = new Bitmap(bitmap);
        if (temp != null) temp.Dispose();
        bitmap.Dispose();
   }

此代码完美运行。

但是当我将<Window>标签更改为<UserControl>(因为我希望它自己嵌入UserControl)时,它不会绘画!

为什么不画在a上UserControl

为什么我不使用ImageWPF? Image线程使用确实令人困惑,每当我尝试在 上绘画时ImageBitmap之前都已处理。

4

1 回答 1

4

您可以简单地使用 WPF Image 控件,而不是 WindowsFormsHost 中的 PictureBox:

<StackPanel Orientation="Horizontal">
    <Image x:Name="image" Height="440" Width="690" HorizontalAlignment="Left"/>
    ...
</StackPanel>

您现在将使用此答案此答案中所示的代码从 Bitmap 对象创建一个 BitmapImage ,并额外调用Freeze它使其可以在 UI 线程中访问:

Bitmap bitmap = eventArgs.Frame; // your NewFrameEventArgs
BitmapImage bitmapImage = new BitmapImage();

using (var stream = new MemoryStream())
{
    bitmap.Save(stream, ImageFormat.Bmp);
    stream.Seek(0, SeekOrigin.Begin);

    bitmapImage.BeginInit();
    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
    bitmapImage.StreamSource = stream;
    bitmapImage.EndInit();
}

bitmapImage.Freeze();

最后,您将通过调用其 Dispatcher 来更新 UI 线程中的 Image 控件:

image.Dispatcher.Invoke((Action)(() => image.Source = bitmapImage));
于 2013-08-08T17:00:49.177 回答