By popular demand, I’ve added an example of how to use the WPFSVL with NAudio as the sound engine powering it. I’m still plugging away at the “getting started” documentation for both BASS and NAudio, but if you get the latest source for WPFSVL, you’ll now have an example application to work from. The way I do sample updates and stereo FFT updates is actually a bit different from anything included in the normal NAudio examples, so I encourage you NAudioers to check it out. The normal examples do FFT at every complete sampling. I have it set up to only do FFT on request from the spectrum analyzer, so my performance seems a bit snappier than other NAudio sample applications out there.
I haven’t had as much time to work out the kinks in the NAudio example, so let me know if you’re seeing anything odd. I know I’m still struggling with certain MP3 files returning strange level data on the waveform. Also, since NAudio is managed code, the performance isn’t quite as snappy as the BASS examples (but still quite decent).
I’ve just launched my first CodePlex project, The WPF Sound Visualization Library. This thing is actually an extension of the Spectrum Analyzer control I made and part of a much larger secret project. Essentially, I’m taking all the WPF controls I’m creating in my other big project, dumping them out to their own project, slapping an MIT license on it, and releasing it to the public. They all have the common theme of being controls related to sound visualization/playback. Everything was designed so the look could be customized. I’m always looking for ways to improve their flexibility, so if you have ideas, let me know.
Stereo Waveform Timeline
First up is a Waveform. I’ve seen a few people struggling to create these on the BASS forums, so I hope this is useful to the community. Right now, it only has stereo support. I hope to support Mono, Quad, and 5.1 channel displays soon. Aside from displaying a Waveform, this thing has the ability to set track position and a repeat section in the audio stream it is rendering.
One of the challenges in displaying a Waveform in WPF is making sure that it doesn’t kill performance while not appearing blurry. I’ve taken advantage of BitmapCache and some special scaling code so that this is handled well. The Waveform Timeline is broken down into four template parts: the waveform canvas, the timeline canvas, the progress indicator canvas, and the repeat region overlay canvas.
Spectrum Analyzer
Next is my old friend the Spectrum Analyzer. Nothing really new to report here. I have lots of detail on this in my previous blog posts. I should note, however, there are a few minor fixes and an added property or two since the last time I posted Spectrum Analyzer source code to this blog.
Album Art Display
Finally, we have an album art display. Basically, it’ll take the album art image (presumably from MP3/AAC tags) and display it in a jewel case. I don’t know how much longer the kids will even remember jewel cases, but I still think they look cool in media applications. I’ve had the Album Art Display in a few of my example applications already, but I’ve refactored it a bit so it was a Control rather than a UserControl.
UPDATE:The WPF Spectrum Analyzer is now part of the WPF Sound Visualization Library. That is where you will find source code for the latest and most-stable versions of the Spectrum Analyzer.
—
A number of weeks ago, I shared with the world a WPF Spectrum Analyzer UserControl I had created. This post is an update on that. Why is there an update? Well, I’ve made some pretty fundamental changes to the Spectrum Analyzer. Not changes that an end-user would necessarily notice at first glance, but they’re fundamental to the way the control performs. I was dissatisfied with the first iteration of the Spectrum Analyzer for two reasons:
- It didn’t support scaling.
- It was a UserControl, which means that didn’t support custom templates/themes.
These two inadequacies severely crippled much of what makes WPF so great.
Supporting Scaling – Go Go Gadget Vectors!
My first pass at the Spectrum Analyzer was based on a very bad assumption. I assumed, foolishly, that a classic pixel-based rendering loop where I manually controlled the buffers would offer me performance benefits and control that I would not be able to achieve if I used vector-based rendering techniques. When I say “vector-based” I mean rendering Shapes on a Canvas. “Pixel-based” refers to me using a DrawingContext to draw shapes in a fashion similar to how things were done in the ol’ GDI+ days. I’ve left my old post in tact if you want to see how the pixel-based technique was done. Assumption aside, using pixel-based rendering has some consequences when a ScaleTransform gets applied to my control. Basically, things get blurry. It’s the same as resizing an image in Photoshop (that is, in the real world, where we don’t have CSI-like “enhance” commands). Since I’m a big proponent of using ScaleTransforms to “zoom” in on a Window’s content as the Window resizes, I felt like this inadequacy in my control was eating away at my soul.
To set about changing this, I had to first mentally break down the control into vector components. Luckily, the Spectrum Analyzer isn’t terribly complex. It’s essentially a variable number of rectangles laid out horizontally. Then, added to that, is another set of rectangles (of the same quantity) that make up the “falling peaks.”
Template Support
This brings us to crafting the control as an ACTUAL Control rather than a UserControl. Really, the only component I require is a Canvas on which I can draw all these Rectangles. I’ve set up my Control using the conventional “PART_” naming convention (see TemplatePartAttribute). To actually get the bars or falling peaks to draw, an application author will also need to define the BarStyle and/or PeakStyle dependency properties on the control. Without these, they’ll still technically “draw,” but they’ll have no brush and be invisible.
Here’s an example of a style and template for the SpectrumAnalyzer control.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | <LinearGradientBrush x:Key="SpectrumBarBrush" EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#06799F" Offset="0" /> <GradientStop Color="#024E68" Offset="1" /> </LinearGradientBrush> <SolidColorBrush x:Key="SpectrumPeakBrush" Color="#61B4CF" /> <Style TargetType="{x:Type local:SpectrumAnalyzer}"> <Setter Property="BarCount" Value="32" /> <Setter Property="BarSpacing" Value="5" /> <Setter Property="BarStyle"> <Setter.Value> <Style TargetType="{x:Type Rectangle}"> <Setter Property="Fill" Value="{StaticResource SpectrumBarBrush}" /> <Setter Property="RadiusX" Value="3" /> <Setter Property="RadiusY" Value="3" /> </Style> </Setter.Value> </Setter> <Setter Property="PeakStyle"> <Setter.Value> <Style TargetType="{x:Type Rectangle}"> <Setter Property="Fill" Value="{StaticResource SpectrumPeakBrush}" /> <Setter Property="RadiusX" Value="3" /> <Setter Property="RadiusY" Value="3" /> </Style> </Setter.Value> </Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:SpectrumAnalyzer}"> <Canvas Name="PART_SpectrumCanvas" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ClipToBounds="True" /> </ControlTemplate> </Setter.Value> </Setter> </Style> |
Revised Control Code
I’ve revised the rendering process a bit. When I first wrote the control code, there was a render method that drew a bunch of rectangles onto a DrawingVisual. Instead of drawing directly, I now just change the coordinates/size of a bunch of rectangles that are stored as fields on the Spectrum Analyzer. I let WPF handle their rendering. Thus, my “RenderSpectrumLines” method became a “UpdateSpectrumShapes” method. Also, since this is now a control, there is no XAML to go along with it per se. However, there would be a default template for it if it were placed in a Control Library. Here’s the updated code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 | [TemplatePart(Name = "PART_SpectrumCanvas", Type = typeof(Canvas))] public class SpectrumAnalyzer : Control { #region Fields private readonly DispatcherTimer animationTimer; private Canvas spectrumCanvas; private ISpectrumPlayer soundPlayer; private readonly List<Shape> barShapes = new List<Shape>(); private readonly List<Shape> peakShapes = new List<Shape>(); private double[] barHeights; private double[] peakHeights; private float[] channelData = new float[2048]; private float[] channelPeakData; private double bandWidth = 1.0; private double barWidth = 1; private int maximumFrequencyIndex = 2047; private int minimumFrequencyIndex; private int[] barIndexMax; private int[] barLogScaleIndexMax; #endregion #region Constants private const int scaleFactorLinear = 9; private const int scaleFactorSqr = 2; private const double minDBValue = -90; private const double maxDBValue = 0; private const double dbScale = (maxDBValue - minDBValue); #endregion #region Dependency Properties #region MaximumFrequency public static readonly DependencyProperty MaximumFrequencyProperty = DependencyProperty.Register("MaximumFrequency", typeof(int), typeof(SpectrumAnalyzer), new UIPropertyMetadata(20000, OnMaximumFrequencyChanged, OnCoerceMaximumFrequency)); private static object OnCoerceMaximumFrequency(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceMaximumFrequency((int)value); else return value; } private static void OnMaximumFrequencyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnMaximumFrequencyChanged((int)e.OldValue, (int)e.NewValue); } protected virtual int OnCoerceMaximumFrequency(int value) { if ((int)value < MinimumFrequency) return MinimumFrequency + 1; return value; } protected virtual void OnMaximumFrequencyChanged(int oldValue, int newValue) { UpdateBarLayout(); } /// <summary> /// The maximum display frequency (right side) for the spectrum analyzer. /// </summary> /// <remarks>In usual practice, this value should be somewhere between 0 and half of the maximum sample rate. If using /// the maximum sample rate, this would be roughly 22000.</remarks> [Category("Common")] public int MaximumFrequency { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (int)GetValue(MaximumFrequencyProperty); } set { SetValue(MaximumFrequencyProperty, value); } } #endregion #region Minimum Frequency public static readonly DependencyProperty MinimumFrequencyProperty = DependencyProperty.Register("MinimumFrequency", typeof(int), typeof(SpectrumAnalyzer), new UIPropertyMetadata(20, OnMinimumFrequencyChanged, OnCoerceMinimumFrequency)); private static object OnCoerceMinimumFrequency(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceMinimumFrequency((int)value); else return value; } private static void OnMinimumFrequencyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnMinimumFrequencyChanged((int)e.OldValue, (int)e.NewValue); } protected virtual int OnCoerceMinimumFrequency(int value) { if (value < 0) return value = 0; CoerceValue(MaximumFrequencyProperty); return value; } protected virtual void OnMinimumFrequencyChanged(int oldValue, int newValue) { UpdateBarLayout(); } /// <summary> /// The minimum display frequency (left side) for the spectrum analyzer. /// </summary> [Category("Common")] public int MinimumFrequency { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (int)GetValue(MinimumFrequencyProperty); } set { SetValue(MinimumFrequencyProperty, value); } } #endregion #region BarCount public static readonly DependencyProperty BarCountProperty = DependencyProperty.Register("BarCount", typeof(int), typeof(SpectrumAnalyzer), new UIPropertyMetadata(32, OnBarCountChanged, OnCoerceBarCount)); private static object OnCoerceBarCount(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceBarCount((int)value); else return value; } private static void OnBarCountChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnBarCountChanged((int)e.OldValue, (int)e.NewValue); } protected virtual int OnCoerceBarCount(int value) { value = Math.Max(value, 1); return value; } protected virtual void OnBarCountChanged(int oldValue, int newValue) { UpdateBarLayout(); } /// <summary> /// The number of bars to show on the sprectrum analyzer. /// </summary> /// <remarks>A bar's width can be a minimum of 1 pixel. If the BarSpacing and BarCount property result /// in the bars being wider than the chart itself, the BarCount will automatically scale down.</remarks> [Category("Common")] public int BarCount { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (int)GetValue(BarCountProperty); } set { SetValue(BarCountProperty, value); } } #endregion #region BarSpacing public static readonly DependencyProperty BarSpacingProperty = DependencyProperty.Register("BarSpacing", typeof(double), typeof(SpectrumAnalyzer), new UIPropertyMetadata(5.0d, OnBarSpacingChanged, OnCoerceBarSpacing)); private static object OnCoerceBarSpacing(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceBarSpacing((double)value); else return value; } private static void OnBarSpacingChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnBarSpacingChanged((double)e.OldValue, (double)e.NewValue); } protected virtual double OnCoerceBarSpacing(double value) { value = Math.Max(value, 0); return value; } protected virtual void OnBarSpacingChanged(double oldValue, double newValue) { UpdateBarLayout(); } /// <summary> /// The spacing, in pixels, between the bars. /// </summary> [Category("Common")] public double BarSpacing { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (double)GetValue(BarSpacingProperty); } set { SetValue(BarSpacingProperty, value); } } #endregion #region PeakFallDelay public static readonly DependencyProperty PeakFallDelayProperty = DependencyProperty.Register("PeakFallDelay", typeof(int), typeof(SpectrumAnalyzer), new UIPropertyMetadata(10, OnPeakFallDelayChanged, OnCoercePeakFallDelay)); private static object OnCoercePeakFallDelay(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoercePeakFallDelay((int)value); else return value; } private static void OnPeakFallDelayChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnPeakFallDelayChanged((int)e.OldValue, (int)e.NewValue); } protected virtual int OnCoercePeakFallDelay(int value) { value = Math.Max(value, 0); return value; } protected virtual void OnPeakFallDelayChanged(int oldValue, int newValue) { } /// <summary> /// The delay factor for the peaks falling. This is relative to the /// refresh rate of the chart. /// </summary> [Category("Common")] public int PeakFallDelay { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (int)GetValue(PeakFallDelayProperty); } set { SetValue(PeakFallDelayProperty, value); } } #endregion #region IsFrequencyScaleLinear public static readonly DependencyProperty IsFrequencyScaleLinearProperty = DependencyProperty.Register("IsFrequencyScaleLinear", typeof(bool), typeof(SpectrumAnalyzer), new UIPropertyMetadata(false, OnIsFrequencyScaleLinearChanged, OnCoerceIsFrequencyScaleLinear)); private static object OnCoerceIsFrequencyScaleLinear(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceIsFrequencyScaleLinear((bool)value); else return value; } private static void OnIsFrequencyScaleLinearChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnIsFrequencyScaleLinearChanged((bool)e.OldValue, (bool)e.NewValue); } protected virtual bool OnCoerceIsFrequencyScaleLinear(bool value) { return value; } protected virtual void OnIsFrequencyScaleLinearChanged(bool oldValue, bool newValue) { UpdateBarLayout(); } /// <summary> /// If true, the bars will represent frequency buckets on a linear scale (making them all /// have equal band widths on the frequency scale). Otherwise, the bars will be layed out /// on a logrithmic scale, with each bar having a larger bandwidth than the one previous. /// </summary> [Category("Common")] public bool IsFrequencyScaleLinear { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (bool)GetValue(IsFrequencyScaleLinearProperty); } set { SetValue(IsFrequencyScaleLinearProperty, value); } } #endregion #region BarHeightScaling public static readonly DependencyProperty BarHeightScalingProperty = DependencyProperty.Register("BarHeightScaling", typeof(BarHeightScalingStyles), typeof(SpectrumAnalyzer), new UIPropertyMetadata(BarHeightScalingStyles.Decibel, OnBarHeightScalingChanged, OnCoerceBarHeightScaling)); private static object OnCoerceBarHeightScaling(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceBarHeightScaling((BarHeightScalingStyles)value); else return value; } private static void OnBarHeightScalingChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnBarHeightScalingChanged((BarHeightScalingStyles)e.OldValue, (BarHeightScalingStyles)e.NewValue); } protected virtual BarHeightScalingStyles OnCoerceBarHeightScaling(BarHeightScalingStyles value) { return value; } protected virtual void OnBarHeightScalingChanged(BarHeightScalingStyles oldValue, BarHeightScalingStyles newValue) { } /// <summary> /// If true, the bar height will be displayed linearly with the intensity value. /// Otherwise, the bars will be scaled with a square root function. /// </summary> [Category("Common")] public BarHeightScalingStyles BarHeightScaling { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (BarHeightScalingStyles)GetValue(BarHeightScalingProperty); } set { SetValue(BarHeightScalingProperty, value); } } #endregion #region AveragePeaks public static readonly DependencyProperty AveragePeaksProperty = DependencyProperty.Register("AveragePeaks", typeof(bool), typeof(SpectrumAnalyzer), new UIPropertyMetadata(false, OnAveragePeaksChanged, OnCoerceAveragePeaks)); private static object OnCoerceAveragePeaks(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceAveragePeaks((bool)value); else return value; } private static void OnAveragePeaksChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnAveragePeaksChanged((bool)e.OldValue, (bool)e.NewValue); } protected virtual bool OnCoerceAveragePeaks(bool value) { return value; } protected virtual void OnAveragePeaksChanged(bool oldValue, bool newValue) { } /// <summary> /// If true, each bar's peak value will be averaged with the previous /// bar's peak. This creates a smoothing effect on the bars. /// </summary> [Category("Common")] public bool AveragePeaks { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (bool)GetValue(AveragePeaksProperty); } set { SetValue(AveragePeaksProperty, value); } } #endregion #region BarStyle public static readonly DependencyProperty BarStyleProperty = DependencyProperty.Register("BarStyle", typeof(Style), typeof(SpectrumAnalyzer), new UIPropertyMetadata(null, new PropertyChangedCallback(OnBarStyleChanged), new CoerceValueCallback(OnCoerceBarStyle))); private static object OnCoerceBarStyle(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceBarStyle((Style)value); else return value; } private static void OnBarStyleChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnBarStyleChanged((Style)e.OldValue, (Style)e.NewValue); } protected virtual Style OnCoerceBarStyle(Style value) { return value; } protected virtual void OnBarStyleChanged(Style oldValue, Style newValue) { UpdateBarLayout(); } /// <summary> /// A style with which to draw the bars on the spectrum analyzer. /// </summary> public Style BarStyle { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (Style)GetValue(BarStyleProperty); } set { SetValue(BarStyleProperty, value); } } #endregion #region PeakStyle public static readonly DependencyProperty PeakStyleProperty = DependencyProperty.Register("PeakStyle", typeof(Style), typeof(SpectrumAnalyzer), new UIPropertyMetadata(null, new PropertyChangedCallback(OnPeakStyleChanged), new CoerceValueCallback(OnCoercePeakStyle))); private static object OnCoercePeakStyle(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoercePeakStyle((Style)value); else return value; } private static void OnPeakStyleChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnPeakStyleChanged((Style)e.OldValue, (Style)e.NewValue); } protected virtual Style OnCoercePeakStyle(Style value) { return value; } protected virtual void OnPeakStyleChanged(Style oldValue, Style newValue) { UpdateBarLayout(); } /// <summary> /// A style with which to draw the falling peaks on the spectrum analyzer. /// </summary> public Style PeakStyle { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (Style)GetValue(PeakStyleProperty); } set { SetValue(PeakStyleProperty, value); } } #endregion #region ActualBarWidth public static readonly DependencyProperty ActualBarWidthProperty = DependencyProperty.Register("ActualBarWidth", typeof(double), typeof(SpectrumAnalyzer), new UIPropertyMetadata(0.0d, new PropertyChangedCallback(OnActualBarWidthChanged), new CoerceValueCallback(OnCoerceActualBarWidth))); private static object OnCoerceActualBarWidth(DependencyObject o, object value) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) return spectrumAnalyzer.OnCoerceActualBarWidth((double)value); else return value; } private static void OnActualBarWidthChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { SpectrumAnalyzer spectrumAnalyzer = o as SpectrumAnalyzer; if (spectrumAnalyzer != null) spectrumAnalyzer.OnActualBarWidthChanged((double)e.OldValue, (double)e.NewValue); } protected virtual double OnCoerceActualBarWidth(double value) { return value; } protected virtual void OnActualBarWidthChanged(double oldValue, double newValue) { } /// <summary> /// The actual width that the bars will be drawn at. /// </summary> public double ActualBarWidth { // IMPORTANT: To maintain parity between setting a property in XAML and procedural code, do not touch the getter and setter inside this dependency property! get { return (double)GetValue(ActualBarWidthProperty); } protected set { SetValue(ActualBarWidthProperty, value); } } #endregion #endregion #region Enums /// <summary> /// The different ways that the bar height can be scaled by the spectrum analyzer. /// </summary> public enum BarHeightScalingStyles { /// <summary> /// A decibel scale. Formula: 20 * Log10(FFTValue). Total bar height /// is scaled from -90 to 0 dB. /// </summary> Decibel, /// <summary> /// A non-linear squareroot scale. Formula: Sqrt(FFTValue) * 2 * BarHeight. /// </summary> Sqrt, /// <summary> /// A linear scale. Formula: 9 * FFTValue * BarHeight. /// </summary> Linear } /// <summary> /// The styles that the spectrum analyzer can draw the bars. /// </summary> public enum BarDrawingStyles { /// <summary> /// Square bars. /// </summary> Square, /// <summary> /// Rounded bars with the corner radius as half the /// bar width. /// </summary> Rounded } #endregion #region Template Overrides public override void OnApplyTemplate() { spectrumCanvas = GetTemplateChild("PART_SpectrumCanvas") as Canvas; UpdateBarLayout(); } #endregion #region Constructors static SpectrumAnalyzer() { DefaultStyleKeyProperty.OverrideMetadata(typeof(SpectrumAnalyzer), new FrameworkPropertyMetadata(typeof(SpectrumAnalyzer))); } public SpectrumAnalyzer() { animationTimer = new DispatcherTimer(DispatcherPriority.ApplicationIdle) { Interval = TimeSpan.FromMilliseconds(25), }; animationTimer.Tick += animationTimer_Tick; } #endregion #region Public Methods /// <summary> /// Register a sound player from which the spectrum analyzer /// can get the necessary playback data. /// </summary> /// <param name="soundPlayer">A sound player that provides spectrum data through the ISpectrumPlayer interface methods.</param> public void RegisterSoundPlayer(ISpectrumPlayer soundPlayer) { this.soundPlayer = soundPlayer; soundPlayer.PropertyChanged += soundPlayer_PropertyChanged; UpdateBarLayout(); animationTimer.Start(); } #endregion #region Event Overrides protected override void OnRender(DrawingContext dc) { base.OnRender(dc); UpdateBarLayout(); UpdateSpectrum(); } protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) { base.OnRenderSizeChanged(sizeInfo); UpdateBarLayout(); UpdateSpectrum(); } #endregion #region Private Drawing Methods private void UpdateSpectrum() { if (soundPlayer == null || spectrumCanvas == null || spectrumCanvas.RenderSize.Width < 1 || spectrumCanvas.RenderSize.Height < 1) return; if (soundPlayer.IsPlaying && (soundPlayer.GetFFTData(channelData) < 1)) return; UpdateSpectrumShapes(); } private void UpdateSpectrumShapes() { bool allZero = true; double fftBucketHeight = 0f; double barHeight = 0f; double lastPeakHeight = 0f; double peakYPos = 0f; double height = spectrumCanvas.RenderSize.Height; int barIndex = 0; double peakDotHeight = Math.Max(barWidth / 2.0f, 1); double barHeightScale = (height - peakDotHeight); for (int i = minimumFrequencyIndex; i <= maximumFrequencyIndex; i++) { // If we're paused, keep drawing, but set the current height to 0 so the peaks fall. if (!soundPlayer.IsPlaying) { barHeight = 0f; } else // Draw the maximum value for the bar's band { switch (BarHeightScaling) { case BarHeightScalingStyles.Decibel: double dbValue = 20 * Math.Log10((double)channelData[i]); fftBucketHeight = ((dbValue - minDBValue) / dbScale) * barHeightScale; break; case BarHeightScalingStyles.Linear: fftBucketHeight = (channelData[i] * scaleFactorLinear) * barHeightScale; break; case BarHeightScalingStyles.Sqrt: fftBucketHeight = (((Math.Sqrt((double)channelData[i])) * scaleFactorSqr) * barHeightScale); break; } if (barHeight < fftBucketHeight) barHeight = fftBucketHeight; if (barHeight < 0f) barHeight = 0f; } // If this is the last FFT bucket in the bar's group, draw the bar. int currentIndexMax = IsFrequencyScaleLinear ? barIndexMax[barIndex] : barLogScaleIndexMax[barIndex]; if (i == currentIndexMax) { // Peaks can't surpass the height of the control. if (barHeight > height) barHeight = height; if (AveragePeaks && barIndex > 0) barHeight = (lastPeakHeight + barHeight) / 2; peakYPos = barHeight; if (channelPeakData[barIndex] < peakYPos) channelPeakData[barIndex] = (float)peakYPos; else channelPeakData[barIndex] = (float)(peakYPos + (PeakFallDelay * channelPeakData[barIndex])) / ((float)(PeakFallDelay + 1)); double xCoord = BarSpacing + (barWidth * barIndex) + (BarSpacing * barIndex) + 1; barShapes[barIndex].Margin = new Thickness(xCoord, (height - 1) - barHeight, 0, 0); barShapes[barIndex].Height = barHeight; peakShapes[barIndex].Margin = new Thickness(xCoord, (height - 1) - channelPeakData[barIndex] - peakDotHeight, 0, 0); peakShapes[barIndex].Height = peakDotHeight; if (channelPeakData[barIndex] > 0.05) allZero = false; lastPeakHeight = barHeight; barHeight = 0f; barIndex++; } } if (allZero && !soundPlayer.IsPlaying) animationTimer.Stop(); } private void UpdateBarLayout() { if (soundPlayer == null || spectrumCanvas == null) return; barWidth = Math.Max(((double)(spectrumCanvas.RenderSize.Width - (BarSpacing * (BarCount + 1))) / (double)BarCount), 1); maximumFrequencyIndex = Math.Min(soundPlayer.GetFFTFrequencyIndex(MaximumFrequency) + 1, 2047); minimumFrequencyIndex = Math.Min(soundPlayer.GetFFTFrequencyIndex(MinimumFrequency), 2047); bandWidth = Math.Max(((double)(maximumFrequencyIndex - minimumFrequencyIndex)) / spectrumCanvas.RenderSize.Width, 1.0); int actualBarCount; if (barWidth >= 1.0d) actualBarCount = BarCount; else actualBarCount = Math.Max((int)((spectrumCanvas.RenderSize.Width - BarSpacing) / (barWidth + BarSpacing)), 1); channelPeakData = new float[actualBarCount]; int indexCount = maximumFrequencyIndex - minimumFrequencyIndex; int linearIndexBucketSize = (int)Math.Round((double)indexCount / (double)actualBarCount, 0); List<int> maxIndexList = new List<int>(); List<int> maxLogScaleIndexList = new List<int>(); double maxLog = Math.Log(actualBarCount, actualBarCount); for (int i = 1; i < actualBarCount; i++) { maxIndexList.Add(minimumFrequencyIndex + (i * linearIndexBucketSize)); int logIndex = (int)((maxLog - Math.Log((actualBarCount + 1) - i, (actualBarCount + 1))) * indexCount) + minimumFrequencyIndex; maxLogScaleIndexList.Add(logIndex); } maxIndexList.Add(maximumFrequencyIndex); maxLogScaleIndexList.Add(maximumFrequencyIndex); barIndexMax = maxIndexList.ToArray(); barLogScaleIndexMax = maxLogScaleIndexList.ToArray(); barHeights = new double[actualBarCount]; peakHeights = new double[actualBarCount]; spectrumCanvas.Children.Clear(); barShapes.Clear(); peakShapes.Clear(); double height = spectrumCanvas.RenderSize.Height; double peakDotHeight = Math.Max(barWidth / 2.0f, 1); for (int i = 0; i < actualBarCount; i++) { double xCoord = BarSpacing + (barWidth * i) + (BarSpacing * i) + 1; Rectangle barRectangle = new Rectangle() { Margin = new Thickness(xCoord, height, 0, 0), Width = barWidth, Height = 0, Style = BarStyle }; barShapes.Add(barRectangle); Rectangle peakRectangle = new Rectangle() { Margin = new Thickness(xCoord, height - peakDotHeight, 0, 0), Width = barWidth, Height = peakDotHeight, Style = PeakStyle }; peakShapes.Add(peakRectangle); } foreach (Shape shape in barShapes) spectrumCanvas.Children.Add(shape); foreach (Shape shape in peakShapes) spectrumCanvas.Children.Add(shape); ActualBarWidth = barWidth; } #endregion #region Event Handlers private void soundPlayer_PropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case "IsPlaying": if (soundPlayer.IsPlaying && !animationTimer.IsEnabled) animationTimer.Start(); break; } } private void animationTimer_Tick(object sender, EventArgs e) { UpdateSpectrum(); } #endregion } |
On Performance / Conclusion
So, where does this leave us? A peak at the Task Manager delivers a pretty telling tale. On my system, the control continues to use very little processor power. What’s even better, however, is you’ll see far less churning of the memory usage. It seems that when you let WPF handle the rendering, it gets to have better control of what sort of buffers get created and how quickly they’re cleared from memory. When we did it manually with our RenderTargetBitmap, we were at the mercy of the garbage collector.
I think there are still a number of controls where one will need to fall back on to pixel based rendering (e.g., a spectrogram), but this one lent itself well to being drawn with vectors. That said, I think the current iteration of this Control is far closer to how one should design their controls for other people to use. People incorporating this into their own applications should find it much more flexible in style, as well as much more performant.
A few years back, we were demonstrating a WinForms application we’d just spent a few years developing to the Vice President of the R&D department. Things were starting to come together and look really nice. Many tough battles were fought to develop custom real-time controls and get everything laid out properly. Months, to years, of effort went into choosing colors and gradients that were easy on the eyes. Hell, we’d even gone out of our way to get in decent support for higher, non-default DPI settings. All-in-all, we were pretty proud of the UX for this application. So, the VP was sitting there, toying around with the application. Then he maximizes the window. The application does exactly what it is supposed to. It fills up all 26 inches of his fancy high-resolution monitor. Everything is docked properly, so the main datagrid on the form expands both vertically and horizontally. The Ribbon Bar at the top of the application keeps its height and the navigation pane on the side keeps its width. Everything seems to be going well.
The VP then asks a fairly innocuous question that really drives home why WinForms is obsolete on modern displays. He asks something along the lines of “why is it that when I maximize this window, things don’t get bigger?” We’re a little confused and reply, “Things did get bigger. As you can see, the data grid grew.” He retorts “No, no. There is more data on the screen, but all of the fonts and everything stay the same size. It’d be nice if things got *bigger* so they were easier to read on these really high-resolution monitors.” Now, if any of you have ever attempted to deal with this sort of request in WinForms, you’ll understand exactly why this is VERY hard to achieve. WinForms is pixel-based and very much resolution-dependent. Fulfilling the request to have things zoom/scale in WinForms falls somewhere just short of impossible. It would certainly take a massive amount of infrastructure coding to do this with much success, and forget about using a third-party control library (or even the standard set of controls).
Luckily, our VP wasn’t the only person in the world to have this request. Microsoft noted this issue and seems to have built WPF around this very problem. However, it intrigues me that more people have not seemed to clue in on this new way of scaling their application’s Window. I’ve seen it out there, but only in about of a quarter of the WPF applications I’ve tried. I think either people aren’t aware of this new method or don’t know of a nice, robust way to implement it so that simply resizing the Window causes your UI elements to scale-up.
Implementing Scaling
At the heart of this scaling solution, there are two concepts at work. First, there is a LayoutTransform that will be applied at very root-most content element of your Window. Secondly, there will be some resize-detection logic in the Window to determine what sort of scaling needs to happen.
First, we’ll start with the XAML where we define the LayoutTransform. Give your main grid a name (or whatever your root element is: border, etc.). Also hook up its SizeChanged event. We’ll come back to that. It’ll be important to also define a minimum width and height for the form, as scaling it too small will make it impossible to read. In the LayoutTransform, define a ScaleTransform. This ScaleTransform will have the ScaleX and ScaleY value uniformly bound to the certain ScaleValue. The ScaleValue will be essentially the percentage of zoom we’ll employ. If that value is 1.2, you can expect your controls to be zoomed in at 120%. To phrase it another way, we’re attempting to zoom-to-fill all of our contents before attempting to refactor our layout using the docking configuration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Name="myMainWindow" Width="500" Height="400" MinWidth="250" MinHeight="200"> <Grid Name="MainGrid" SizeChanged="MainGrid_SizeChanged"> <Grid.LayoutTransform> <ScaleTransform x:Name="ApplicationScaleTransform" CenterX="0" CenterY="0" ScaleX="{Binding ElementName=myMainWindow, Path=ScaleValue}" ScaleY="{Binding ElementName=myMainWindow, Path=ScaleValue}" /> </Grid.LayoutTransform> <!-- Window Content Here --> </Grid> |
Now, in the code-behind, we’ll be creating a ScaleValue dependency property for the ScaleTransform to bind to. This ScaleValue is set whenever the size of the Window changes. The value is calculated based on the current width or height divided by the designed-for width or height. We take the lower of those two values and make that our scaling mechanism. This makes the zoom effect similar to what you’re used to seeing when you use a Viewbox when the StretchDirection is “Both” and the Stretch style is “Fill.”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | public partial class MainWindow : Window { #region ScaleValue Depdency Property public static readonly DependencyProperty ScaleValueProperty = DependencyProperty.Register("ScaleValue", typeof(double), typeof(MainWindow), new UIPropertyMetadata(1.0, new PropertyChangedCallback(OnScaleValueChanged), new CoerceValueCallback(OnCoerceScaleValue))); private static object OnCoerceScaleValue(DependencyObject o, object value) { MainWindow mainWindow = o as MainWindow; if (mainWindow != null) return mainWindow.OnCoerceScaleValue((double)value); else return value; } private static void OnScaleValueChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { MainWindow mainWindow = o as MainWindow; if (mainWindow != null) mainWindow.OnScaleValueChanged((double)e.OldValue, (double)e.NewValue); } protected virtual double OnCoerceScaleValue(double value) { if (double.IsNaN(value)) return 1.0d; value = Math.Max(0.1, value); return value; } protected virtual void OnScaleValueChanged(double oldValue, double newValue) { } public double ScaleValue { get { return (double)GetValue(ScaleValueProperty); } set { SetValue(ScaleValueProperty, value); } } #endregion private void MainGrid_SizeChanged(object sender, EventArgs e) { CalculateScale(); } private void CalculateScale() { double yScale = ActualHeight / 400.0d; double xScale = ActualWidth / 500.0d; double value = Math.Min(xScale, yScale); ScaleValue = (double)OnCoerceScaleValue(MainGrid, value); } public MainWindow() { InitializeComponent(); } } |
That’s all there is to it! Beyond increasing the size of your Window, it works surprisingly well when decreasing the window size too, down to a certain level anyway. I find this solution to be robust enough to handle most cases my application, but be sure to read over the next section to understand some caveats.
Caveats
ScaleTransform can cause problems if any of your UI elements are rendered using pixel-based rendering techniques. What happens? Well, when you scale, the bitmap buffers of the controls start to stretch and appear blurry. Luckily, in my experience, very few third party components that were designed for WPF do this kind of pixel-based rendering. Kudos to the majority of WPF control developers for doing things the recommended way. In your own controls, there are a few key areas you need to be aware of where this can be problematic:
- Controls that use the new CacheMode property.
- Controls that use DrawingVisuals, RenderTargetBitmap or WriteableBitmap, and DrawingContext to draw.
- Use of WinForms components in your WPF application.
Dealing With The Caveats
CacheMode: To deal with CacheMode when scaling, you can try using the RenderAtScale property. I do this semi-automatically on my custom controls by including a mechanism to automatically detect what ScaleTransform has been applied to the control. Then, I make the RenderAtScale property the same. I include a “UseAutoScaling” property to allow the control’s user to decide whether or not they want to have this behavior happen in their Application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) { base.OnRenderSizeChanged(sizeInfo); UpdateCacheScaling(); } private void UpdateCacheScaling() { if (myCanvas == null) return; BitmapCache cache = (BitmapCache)myCanvas.CacheMode; if (UseAutoScaling) { double totalTransformScale = GetTotalTransformScale(); if (cache.RenderAtScale != totalTransformScale) cache.RenderAtScale = totalTransformScale; } else { cache.RenderAtScale = 1.0d; } } private double GetTotalTransformScale() { double totalTransform = 1.0d; DependencyObject currentVisualTreeElement = this; do { Visual visual = currentVisualTreeElement as Visual; if (visual != null) { Transform transform = VisualTreeHelper.GetTransform(visual); // This condition is a way of determining if it // was a uniform scale transform. Is there some better way? if ((transform != null) && (transform.Value.M12 == 0) && (transform.Value.M21 == 0) && (transform.Value.OffsetX == 0) && (transform.Value.OffsetY == 0) && (transform.Value.M11 == transform.Value.M22)) { totalTransform *= transform.Value.M11; } } currentVisualTreeElement = VisualTreeHelper.GetParent(currentVisualTreeElement); } while (currentVisualTreeElement != null); return totalTransform; } |
RenderTargetBitmap or WriteableBitmap: I have found no great solution for this. If the control is being drawn using these techniques, the only option is to alter the code such that it renders at a higher scale or change it dramatically to use vector-based drawing. Be aware that even if the control is tricked into drawing at a higher resolution, if it is being rendered to an Image, it will still appear blurry. The scale of the Image will also have to dealt with.
WinForms Controls: Stop using WinForms controls! No seriously, you’re killing your application’s memory usage and performance by dropping these into your WPF application.
I hope this gives you all a starting point to making your WPF application scale. It’d be really nice if more applications featured this ability, even if as a user-preference.








