Click here to Skip to main content
15,892,537 members
Articles / Desktop Programming / WPF
Article

A Solution for Fast BitmapEffects

Rate me:
Please Sign up or sign in to vote.
3.27/5 (7 votes)
27 Apr 2008CPOL1 min read 19.2K   165   9   1
A shameless (and for sure buggy) clone of Identitymine's ElementSnapshot
Image 1

Introduction

If you have used BitmapEffects you probably soon stopped doing so, as they are quite a CPU hog. But here comes your hero: SnapshotPanel!

It simply renders its containing elements only when they're resized and thus makes BitmapEffects blazingly fast.

Using the Code

Without further ado, here comes the code:
(Sorry for missing comments. Maybe I'll fix this sometime. The code for Arrange and Measure is mostly copy pasted from the FishEyePanel project.)

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace WpfTriangelo
{
    class SnapshotPanel: Panel
    {
        RenderTargetBitmap bmp;

        public SnapshotPanel()
        {
            this.Background = Brushes.Transparent;
        }

        bool aSizeChange = true, mSizeChange = true;
        protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
        {
            UpdateSnapshot();
            base.OnRenderSizeChanged(sizeInfo);
        }

        void ChildChangedUpdate(Panel p)
        {
            foreach (UIElement c in p.Children)
            {
                var cinp = c as INotifyPropertyChanged;
                if (cinp != null)
                {
                    cinp.PropertyChanged -=
                         new PropertyChangedEventHandler(cinp_PropertyChanged);
                    cinp.PropertyChanged +=
                         new PropertyChangedEventHandler(cinp_PropertyChanged);
                }
                var cp = c as Panel;
                if (cp != null)
                    ChildChangedUpdate(cp);
            }
        }

        void cinp_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            UpdateSnapshot();
        }

        protected override void OnVisualChildrenChanged
            (DependencyObject visualAdded, DependencyObject visualRemoved)
        {
            base.OnVisualChildrenChanged(visualAdded, visualRemoved);
            ChildChangedUpdate(this);
        }

        private void UpdateSnapshot()
        {
            aSizeChange = mSizeChange = true;
            int w = (int)this.ActualWidth;
            int h = (int)this.ActualHeight;
            w = w > 0 ? w : 1;
            h = h > 0 ? h : 1;
            bmp = new RenderTargetBitmap(w, h, 96, 96, PixelFormats.Pbgra32);
            this.InvalidateVisual();
            var b = BitmapFrame.Create(bmp);
            bmp.Render(this);
            this.Background = new ImageBrush(b);
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            if (this.Children == null || this.Children.Count == 0 || aSizeChange != true)
                return finalSize;

            aSizeChange = false;

            foreach (UIElement child in this.Children)
            {
                child.Arrange(new Rect(0, 0, finalSize.Width, finalSize.Height));
            }

            return finalSize;
        }

        protected override Size MeasureOverride(Size availableSize)
        {
            if (!mSizeChange)
                return availableSize;

            mSizeChange = false;

            Size idealSize = new Size(0, 0);

            // Allow children as much room as they want - then scale them
            //Size size = new Size(Double.PositiveInfinity, Double.PositiveInfinity);
            foreach (UIElement child in Children)
            {
                child.Measure(availableSize);
                idealSize.Width += child.DesiredSize.Width;
                idealSize.Height += child.DesiredSize.Height;
            }

            // EID calls us with infinity, but framework
            // doesn't like us to return infinity

            if (double.IsInfinity(availableSize.Height) ||
                double.IsInfinity(availableSize.Width))
                return idealSize;
            else
                return availableSize;
        }

        protected override Visual GetVisualChild(int index)
        {
            return base.GetVisualChild(index);
        }

        protected override System.Collections.IEnumerator LogicalChildren
        {
            get
            {
                return base.LogicalChildren;
            }
        }

        protected override int VisualChildrenCount
        {
            get
            {
                if (aSizeChange)
                    return base.VisualChildrenCount;
                else
                    return 0;
            }
        }
    }
}

It has only been tested with ONE child and this child should have height and width set. Otherwise, there will be nothing on the screen.

Points of Interest

The real magic in hiding your children lies in VisualChildrenCount. I think it's self-explanatory.

I attached a small test project. Simply remove the SnapshotPanel in the DataTemplate and you will see how slow it works. (I know it loads faster, but you have to make trade-offs.)

PS: The demo project is also a nice example for DataBinding and Converters, as the Dots on the Stones are data bound...

Thanks

Thanks to Josh Smith and Sacha Barber: your articles helped me understand WPF!

History

  • Update 1: Fixed unnecessary Grid and thus rendering of bound elements

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
h32
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
NewsCode Pin
h3228-Apr-08 13:56
h3228-Apr-08 13:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.