【问题标题】:Render (redraw) the invisible canvas渲染(重绘)不可见的画布
【发布时间】:2012-07-12 10:25:30
【问题描述】:

我在每个页面like this 上都有一个带有单独画布(上面有不同的用户控件)的选项卡式应用程序。现在我需要将所有页面(画布)保存到图像。代码是这样的:

public static System.Drawing.Bitmap ExportToImage(Canvas canvas)
{
    // Save old background
    Brush background = canvas.Background;
    // Clear background to make images free of it
    canvas.Background = null;

    //canvas.UpdateLayout();
    //canvas.InvalidateVisual();

    // Create a render bitmap and push the surface to it
    RenderTargetBitmap renderBitmap =
        new RenderTargetBitmap(
            (int)canvas.Width,
            (int)canvas.Height,
            96d,
            96d,
            PixelFormats.Pbgra32);
    renderBitmap.Render(canvas);

    MemoryStream picStream = new MemoryStream();
    PngBitmapEncoder encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
    encoder.Save(picStream);

    canvas.Background = background;

    return new System.Drawing.Bitmap(picStream);
}

我进行了额外的转换,例如更改边距和大小,但这并不重要。

对于活动页面上的画布(当前在屏幕上),我得到正常渲染的图像:没有背景、排列的位置和大小等)。

但对于非活动页面上的画布,我会得到具有原始画布外观的图像(有背景且未排列)。 如何强制画布应用我的修改并使用它们进行渲染? 我尝试在画布上使用 UpdateLayout 和 InvalidateVisual,但没有效果。

【问题讨论】:

  • 您是否尝试过在渲染时以编程方式将选项卡切换到每个画布?我发现我必须这样做才能让 UI 更改影响目标 UIElements - 如果这有效,那么至少你知道问题出在哪里
  • Charleh,这是可能的,但这是不可接受的:它会眨眼太多。此外,可以关闭选项卡,并且完全隐藏一些画布。打开新标签更加不可接受。 :(
  • 必须是一种将 cavas 渲染到不可见表面的方法,以便重绘所有控件 - 有人有一个 WPF 屏幕截图教程,它使用 RenderTargetBitmap 但也使用 DrawingVisual 和 DrawingContext 来应用变换等等 - 也许这会有所帮助(也许它会呈现变化)grumpydev.com/2009/01/03/taking-wpf-screenshots
  • 好的,谢谢你的链接。我在 StackOverflow 上看到了相同的主题。使用 UIElement 作为 Brush 看起来有点不正常……应该有更好的解决方案。 :(此外,我不确定它是否适用于画布,而不适用于 UIElement。
  • Canvas 是一个 UIElement:msdn.microsoft.com/en-us/library/…

标签: c# wpf


【解决方案1】:

WPF 会卸载不可见的对象,这意味着当您离开 Tab 时,它将卸载其上的 UI 控件并加载一组新控件。

为了避免这种行为,我通常使用TabControl 的扩展版本,当您离开它时,它会存储每个TabItemContentPresenter,当您返回该选项卡时,它会重新加载@987654327 @ 而不是重绘所有内容。它占用了更多内存,但是我发现它的性能更好,因为 TabItem 不再需要在切换选项卡时重新创建其上的所有控件。

您应该能够使用它并将您的图像基于为每个TabItem 存储的ContentPresenter

原始代码来自here,尽管该网站已经关闭了几个月,我不知道它搬到了哪里。我对其进行了一些更改,因为我需要允许拖放选项卡项以重新排列它们而不重绘它们,但这不会影响任何事情。

// Extended TabControl which saves the displayed item so you don't get the performance hit of 
// unloading and reloading the VisualTree when switching tabs

// Obtained from http://www.pluralsight-training.net/community/blogs/eburke/archive/2009/04/30/keeping-the-wpf-tab-control-from-destroying-its-children.aspx
// and made a some modifications so it reuses a TabItem's ContentPresenter when doing drag/drop operations

[TemplatePart(Name = "PART_ItemsHolder", Type = typeof(Panel))]
public class TabControlEx : System.Windows.Controls.TabControl
{
    // Holds all items, but only marks the current tab's item as visible
    private Panel _itemsHolder = null;

    // Temporaily holds deleted item in case this was a drag/drop operation
    private object _deletedObject = null;

    public TabControlEx()
        : base()
    {
        // this is necessary so that we get the initial databound selected item
        this.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;
    }

    /// <summary>
    /// if containers are done, generate the selected item
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
    {
        if (this.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
        {
            this.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged;
            UpdateSelectedItem();
        }
    }

    /// <summary>
    /// get the ItemsHolder and generate any children
    /// </summary>
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        _itemsHolder = GetTemplateChild("PART_ItemsHolder") as Panel;
        UpdateSelectedItem();
    }

    /// <summary>
    /// when the items change we remove any generated panel children and add any new ones as necessary
    /// </summary>
    /// <param name="e"></param>
    protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
    {
        base.OnItemsChanged(e);

        if (_itemsHolder == null)
        {
            return;
        }

        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Reset:
                _itemsHolder.Children.Clear();

                if (base.Items.Count > 0)
                {
                    base.SelectedItem = base.Items[0];
                    UpdateSelectedItem();
                }

                break;

            case NotifyCollectionChangedAction.Add:
            case NotifyCollectionChangedAction.Remove:

                // Search for recently deleted items caused by a Drag/Drop operation
                if (e.NewItems != null && _deletedObject != null)
                {
                    foreach (var item in e.NewItems)
                    {
                        if (_deletedObject == item)
                        {
                            // If the new item is the same as the recently deleted one (i.e. a drag/drop event)
                            // then cancel the deletion and reuse the ContentPresenter so it doesn't have to be 
                            // redrawn. We do need to link the presenter to the new item though (using the Tag)
                            ContentPresenter cp = FindChildContentPresenter(_deletedObject);
                            if (cp != null)
                            {
                                int index = _itemsHolder.Children.IndexOf(cp);

                                (_itemsHolder.Children[index] as ContentPresenter).Tag =
                                    (item is TabItem) ? item : (this.ItemContainerGenerator.ContainerFromItem(item));
                            }
                            _deletedObject = null;
                        }
                    }
                }

                if (e.OldItems != null)
                {
                    foreach (var item in e.OldItems)
                    {

                        _deletedObject = item;

                        // We want to run this at a slightly later priority in case this
                        // is a drag/drop operation so that we can reuse the template
                        this.Dispatcher.BeginInvoke(DispatcherPriority.DataBind,
                            new Action(delegate()
                        {
                            if (_deletedObject != null)
                            {
                                ContentPresenter cp = FindChildContentPresenter(_deletedObject);
                                if (cp != null)
                                {
                                    this._itemsHolder.Children.Remove(cp);
                                }
                            }
                        }
                        ));
                    }
                }

                UpdateSelectedItem();
                break;

            case NotifyCollectionChangedAction.Replace:
                throw new NotImplementedException("Replace not implemented yet");
        }
    }

    /// <summary>
    /// update the visible child in the ItemsHolder
    /// </summary>
    /// <param name="e"></param>
    protected override void OnSelectionChanged(SelectionChangedEventArgs e)
    {
        base.OnSelectionChanged(e);
        UpdateSelectedItem();
    }

    /// <summary>
    /// generate a ContentPresenter for the selected item
    /// </summary>
    void UpdateSelectedItem()
    {
        if (_itemsHolder == null)
        {
            return;
        }

        // generate a ContentPresenter if necessary
        TabItem item = GetSelectedTabItem();
        if (item != null)
        {
            CreateChildContentPresenter(item);
        }

        // show the right child
        foreach (ContentPresenter child in _itemsHolder.Children)
        {
            child.Visibility = ((child.Tag as TabItem).IsSelected) ? Visibility.Visible : Visibility.Collapsed;
        }
    }

    /// <summary>
    /// create the child ContentPresenter for the given item (could be data or a TabItem)
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    ContentPresenter CreateChildContentPresenter(object item)
    {
        if (item == null)
        {
            return null;
        }

        ContentPresenter cp = FindChildContentPresenter(item);

        if (cp != null)
        {
            return cp;
        }

        // the actual child to be added.  cp.Tag is a reference to the TabItem
        cp = new ContentPresenter();
        cp.Content = (item is TabItem) ? (item as TabItem).Content : item;
        cp.ContentTemplate = this.SelectedContentTemplate;
        cp.ContentTemplateSelector = this.SelectedContentTemplateSelector;
        cp.ContentStringFormat = this.SelectedContentStringFormat;
        cp.Visibility = Visibility.Collapsed;
        cp.Tag = (item is TabItem) ? item : (this.ItemContainerGenerator.ContainerFromItem(item));
        _itemsHolder.Children.Add(cp);
        return cp;
    }

    /// <summary>
    /// Find the CP for the given object.  data could be a TabItem or a piece of data
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    ContentPresenter FindChildContentPresenter(object data)
    {
        if (data is TabItem)
        {
            data = (data as TabItem).Content;
        }

        if (data == null)
        {
            return null;
        }

        if (_itemsHolder == null)
        {
            return null;
        }

        foreach (ContentPresenter cp in _itemsHolder.Children)
        {
            if (cp.Content == data)
            {
                return cp;
            }
        }

        return null;
    }

    /// <summary>
    /// copied from TabControl; wish it were protected in that class instead of private
    /// </summary>
    /// <returns></returns>
    protected TabItem GetSelectedTabItem()
    {
        object selectedItem = base.SelectedItem;
        if (selectedItem == null)
        {
            return null;
        }

        if (_deletedObject == selectedItem)
        { 

        }

        TabItem item = selectedItem as TabItem;
        if (item == null)
        {
            item = base.ItemContainerGenerator.ContainerFromIndex(base.SelectedIndex) as TabItem;
        }
        return item;
    }
}

在下面按 cmets 编辑

如果这对您不起作用,您可以尝试像平常一样渲染 Canvas,然后以低于 DispatcherPriority.RenderDispatcherPriority 打印它,以便在所有渲染完成后打印。

类似这样的:

public static void ExportToImage(Canvas canvas, System.Drawing.Bitmap bmp)
{
    // Save old background
    Brush background = canvas.Background;
    // Clear background to make images free of it
    canvas.Background = null;


    // Create a render bitmap and push the surface to it
    RenderTargetBitmap renderBitmap =
        new RenderTargetBitmap(
            (int)canvas.Width,
            (int)canvas.Height,
            96d,
            96d,
            PixelFormats.Pbgra32);
    renderBitmap.Render(canvas);

    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, 
    new Action(delegate() 
    {
        MemoryStream picStream = new MemoryStream();
        PngBitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
        encoder.Save(picStream);

        canvas.Background = background;

        // I don't think you can simply return your value here, 
        // so you'll probably need to setup something else to 
        // return your bitmap to your calling code
        bmp = new System.Drawing.Bitmap(picStream);
    }));
}

【讨论】:

  • “WPF 卸载不可见对象”——这看起来很奇怪。当我进行图片渲染时,我得到了画布图像,所以它以某种方式工作。问题是我对这个不可见的画布(背景/排列)所做的修改对不可见的画布没有影响,但对可见的效果很好。
  • @Badiboy 也许尝试在DispatcherPriorityDispatcherPriority.Render 更晚的时间捕获图像,以便给定时间渲染?
  • 我试着把“Thread.Sleep(500);”在更改画布参数和渲染到没有效果的图像之间。这是否意味着延迟不是解决方案?或者优先级以其他方式起作用?
  • @Badiboy Thread.Sleep 仍将在当前线程上运行,该线程在渲染之前执行。 Dispatcher 的工作方式不同。就像有 10 个线程,每个线程都有不同的优先级。例如,在DispatcherPriority.Normal 上运行的所有内容都将在DispatcherPriority.Render 上运行的所有内容之前执行,而DispatcherPriority.Render 始终在DispatcherPriority.Background 上的项目之前执行
  • @Badiboy 您将像正常一样渲染画布,然后运行代码以将其作为图像输出,其调度程序优先级高于渲染,因此画布在打印之前有时间渲染。我认为您使用哪个调度程序并不重要,尽管我通常使用Application.Current.Dispatcher
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 2012-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-13
  • 1970-01-01
相关资源
最近更新 更多