我现在正在尝试实现类似“惰性” VisualBrush的功能。有人知道该怎么做吗?含义:行为类似于VisualBrush,但不会在Visual中的每个更改上更新,而是最大每秒更新一次(或其他)。
我最好应该提供一些背景,说明我为何要这样做以及我猜想我尝试过的事情:)
问题:我现在的工作是提高相当大的WPF应用程序的性能。我跟踪了主要的性能问题(无论如何在UI级别)都是应用程序中使用的一些可视笔刷。该应用程序由带有一些相当复杂的UserControls的“Desktop”区域和一个包含缩小版本的Desktop的Navigation区域组成。导航区域正在使用可视笔刷完成工作。只要“ table 面”项或多或少是静态的,一切都很好。但是,如果元素频繁更改(例如,因为它们包含动画),则VisualBrush会变得疯狂。它们将随着动画的帧率一起更新。降低帧速率当然会有所帮助,但是我正在寻找一种更通用的解决方案。虽然“源”控件仅呈现受动画影响的小区域,但可视画笔容器已完全呈现,从而导致应用程序性能下降。我已经尝试使用BitmapCacheBrush代替。不幸的是没有帮助。动画在控件内部。因此,无论如何都必须刷新画笔。
可能的解决方案:我创建了一个与VisualBrush差不多的控件。它需要一些视觉效果(如VisualBrush),但是正在使用DiapatcherTimer和RenderTargetBitmap来完成这项工作。现在,我正在订阅该控件的LayoutUpdated事件,并且每当它发生更改时,都将安排它进行“渲染”(使用RenderTargetBitmap)。然后,实际渲染由DispatcherTimer触发。这样,控件将以DispatcherTimer的频率最大程度重绘自身。
这是代码:
public sealed class VisualCopy : Border
{
#region private fields
private const int mc_mMaxRenderRate = 500;
private static DispatcherTimer ms_mTimer;
private static readonly Queue<VisualCopy> ms_renderingQueue = new Queue<VisualCopy>();
private static readonly object ms_mQueueLock = new object();
private VisualBrush m_brush;
private DrawingVisual m_visual;
private Rect m_rect;
private bool m_isDirty;
private readonly Image m_content = new Image();
#endregion
#region constructor
public VisualCopy()
{
m_content.Stretch = Stretch.Fill;
Child = m_content;
}
#endregion
#region dependency properties
public FrameworkElement Visual
{
get { return (FrameworkElement)GetValue(VisualProperty); }
set { SetValue(VisualProperty, value); }
}
// Using a DependencyProperty as the backing store for Visual. This enables animation, styling, binding, etc...
public static readonly DependencyProperty VisualProperty =
DependencyProperty.Register("Visual", typeof(FrameworkElement), typeof(VisualCopy), new UIPropertyMetadata(null, OnVisualChanged));
#endregion
#region callbacks
private static void OnVisualChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
var copy = obj as VisualCopy;
if (copy != null)
{
var oldElement = args.OldValue as FrameworkElement;
var newelement = args.NewValue as FrameworkElement;
if (oldElement != null)
{
copy.UnhookVisual(oldElement);
}
if (newelement != null)
{
copy.HookupVisual(newelement);
}
}
}
private void OnVisualLayoutUpdated(object sender, EventArgs e)
{
if (!m_isDirty)
{
m_isDirty = true;
EnqueuInPipeline(this);
}
}
private void OnVisualSizeChanged(object sender, SizeChangedEventArgs e)
{
DeleteBuffer();
PrepareBuffer();
}
private static void OnTimer(object sender, EventArgs e)
{
lock (ms_mQueueLock)
{
try
{
if (ms_renderingQueue.Count > 0)
{
var toRender = ms_renderingQueue.Dequeue();
toRender.UpdateBuffer();
toRender.m_isDirty = false;
}
else
{
DestroyTimer();
}
}
catch (Exception ex)
{
}
}
}
#endregion
#region private methods
private void HookupVisual(FrameworkElement visual)
{
visual.LayoutUpdated += OnVisualLayoutUpdated;
visual.SizeChanged += OnVisualSizeChanged;
PrepareBuffer();
}
private void UnhookVisual(FrameworkElement visual)
{
visual.LayoutUpdated -= OnVisualLayoutUpdated;
visual.SizeChanged -= OnVisualSizeChanged;
DeleteBuffer();
}
private static void EnqueuInPipeline(VisualCopy toRender)
{
lock (ms_mQueueLock)
{
ms_renderingQueue.Enqueue(toRender);
if (ms_mTimer == null)
{
CreateTimer();
}
}
}
private static void CreateTimer()
{
if (ms_mTimer != null)
{
DestroyTimer();
}
ms_mTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(mc_mMaxRenderRate) };
ms_mTimer.Tick += OnTimer;
ms_mTimer.Start();
}
private static void DestroyTimer()
{
if (ms_mTimer != null)
{
ms_mTimer.Tick -= OnTimer;
ms_mTimer.Stop();
ms_mTimer = null;
}
}
private RenderTargetBitmap m_targetBitmap;
private void PrepareBuffer()
{
if (Visual.ActualWidth > 0 && Visual.ActualHeight > 0)
{
const double topLeft = 0;
const double topRight = 0;
var width = (int)Visual.ActualWidth;
var height = (int)Visual.ActualHeight;
m_brush = new VisualBrush(Visual);
m_visual = new DrawingVisual();
m_rect = new Rect(topLeft, topRight, width, height);
m_targetBitmap = new RenderTargetBitmap((int)m_rect.Width, (int)m_rect.Height, 96, 96, PixelFormats.Pbgra32);
m_content.Source = m_targetBitmap;
}
}
private void DeleteBuffer()
{
if (m_brush != null)
{
m_brush.Visual = null;
}
m_brush = null;
m_visual = null;
m_targetBitmap = null;
}
private void UpdateBuffer()
{
if (m_brush != null)
{
var dc = m_visual.RenderOpen();
dc.DrawRectangle(m_brush, null, m_rect);
dc.Close();
m_targetBitmap.Render(m_visual);
}
}
#endregion
}
到目前为止,效果很好。唯一的问题是触发因素。当我使用LayoutUpdated时,即使Visual本身根本没有更改,也会连续触发渲染(这可能是因为应用程序其他部分的动画或其他原因)。 LayoutUpdated只是经常被触发的方式。事实上,我可以跳过触发器,而无需使用任何触发器就可以使用计时器更新控件。没关系我还尝试在Visual中覆盖OnRender并引发一个自定义事件以触发更新。也不起作用,因为当VisualTree内部的某些内容发生更改时,不会调用OnRender。这是我目前最好的镜头。与原始的VisualBrush解决方案相比,它的工作要好得多(至少从性能角度而言)。但我仍在寻找更好的解决方案。
有谁知道如何
a)仅在nessasarry时触发更新
或者
b)用完全不同的方法来完成工作?
谢谢!!!
最佳答案
我已经通过反射使用WPF内部监视了控件的视觉状态。因此,我编写的代码与CompositionTarget.Rendering事件 Hook ,遍历树,并在子树中查找任何更改。我编写该程序是为了拦截被推送到MilCore的数据,然后将其用于自己的目的,因此将此代码视为黑客,仅此而已。如果有帮助,那就太好了。我在.NET 4上使用了它。
首先,遍历树的代码读取状态标志:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Reflection;
namespace MilSnatch.Utils
{
public static class VisualTreeHelperPlus
{
public static IEnumerable<DependencyObject> WalkTree(DependencyObject root)
{
yield return root;
int count = VisualTreeHelper.GetChildrenCount(root);
for (int i = 0; i < count; i++)
{
foreach (var descendant in WalkTree(VisualTreeHelper.GetChild(root, i)))
yield return descendant;
}
}
public static CoreFlags ReadFlags(UIElement element)
{
var fieldInfo = typeof(UIElement).GetField("_flags", BindingFlags.Instance | BindingFlags.NonPublic);
return (CoreFlags)fieldInfo.GetValue(element);
}
public static bool FlagsIndicateUpdate(UIElement element)
{
return (ReadFlags(element) &
(
CoreFlags.ArrangeDirty |
CoreFlags.MeasureDirty |
CoreFlags.RenderingInvalidated
)) != CoreFlags.None;
}
}
[Flags]
public enum CoreFlags : uint
{
AreTransformsClean = 0x800000,
ArrangeDirty = 8,
ArrangeInProgress = 0x20,
ClipToBoundsCache = 2,
ExistsEventHandlersStore = 0x2000000,
HasAutomationPeer = 0x100000,
IsCollapsed = 0x200,
IsKeyboardFocusWithinCache = 0x400,
IsKeyboardFocusWithinChanged = 0x800,
IsMouseCaptureWithinCache = 0x4000,
IsMouseCaptureWithinChanged = 0x8000,
IsMouseOverCache = 0x1000,
IsMouseOverChanged = 0x2000,
IsOpacitySuppressed = 0x1000000,
IsStylusCaptureWithinCache = 0x40000,
IsStylusCaptureWithinChanged = 0x80000,
IsStylusOverCache = 0x10000,
IsStylusOverChanged = 0x20000,
IsVisibleCache = 0x400000,
MeasureDirty = 4,
MeasureDuringArrange = 0x100,
MeasureInProgress = 0x10,
NeverArranged = 0x80,
NeverMeasured = 0x40,
None = 0,
RenderingInvalidated = 0x200000,
SnapsToDevicePixelsCache = 1,
TouchEnterCache = 0x80000000,
TouchesCapturedWithinCache = 0x10000000,
TouchesCapturedWithinChanged = 0x20000000,
TouchesOverCache = 0x4000000,
TouchesOverChanged = 0x8000000,
TouchLeaveCache = 0x40000000
}
}
接下来,Rendering事件的支持代码:
//don't worry about RenderDataWrapper. Just use some sort of WeakReference wrapper for each UIElement
void CompositionTarget_Rendering(object sender, EventArgs e)
{
//Thread.Sleep(250);
Dictionary<int, RenderDataWrapper> newCache = new Dictionary<int, RenderDataWrapper>();
foreach (var rawItem in VisualTreeHelperPlus.WalkTree(m_Root))
{
var item = rawItem as FrameworkElement;
if (item == null)
{
Console.WriteLine("Encountered non-FrameworkElement: " + rawItem.GetType());
continue;
}
int hash = item.GetHashCode();
RenderDataWrapper cacheEntry;
if (!m_Cache.TryGetValue(hash, out cacheEntry))
{
cacheEntry = new RenderDataWrapper();
cacheEntry.SetControl(item);
newCache.Add(hash, cacheEntry);
}
else
{
m_Cache.Remove(hash);
newCache.Add(hash, cacheEntry);
}
//check the visual for updates - something like the following...
if(VisualTreeHelperPlus.FlagsIndicateUpdate(item as UIElement))
{
//flag for new snapshot.
}
}
m_Cache = newCache;
}
无论如何,我以这种方式监视了可视化树中的更新,并且我认为您可以根据需要使用类似的方法来监视它们。这与最佳实践相去甚远,但有时必须要有实用的代码。谨防。
关于wpf - WPF “Lazy” VisualBrush,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5764382/