Practical WPF Charts and Graphics
About this Book
This book follows the same style of my previous book "Practical C# Charts and Graphics". I emphasize the practicality of WPF graphics to your real-world charts and graphics applications and try to explain WPF graphics concepts using code examples. This in-depth book on chart and graphics programming in the Windows Presentation Foundation (WPF) contains a variety of ready-to-run code examples, which provide you with everything you need to add advanced charts and graphics to your applications. These examples teach you how to create various WPF graphics and charts, including the US flag, 2D charts, stock charts, contour charts, 3D surface charts, interactive charts, and 3D graphics models. The book uses code examples to clearly explain every step involved in building a variety of WPF chart and graphics applications.
This book and its sample code listings provide you with:
-
Complete, in-depth instruction on practical chart and graphics programming with C# and WPF. After reading this
book and running the example programs, you will be able to add various sophisticated charts and graphics to
your WPF applications.
-
Ready-to-run example programs that allow you to explore the chart and graphics techniques described in the book.
These examples can be used to better understand how the chart and graphics algorithms work. You can modify the
code examples or add new features to them to form the basis of your own projects. Some of the example code listings
provided in this book are already sophisticated chart and graphics packages that can be used directly in your own
real-world WPF applications.
- Many classes in the sample code listings that you will find useful in your WPF chart and graphics programming. These classes include matrix manipulation, coordinate transformation, color maps, chart controls, and other useful utility classes. You can extract these classes and plug them into your own applications.
Table of Contents
Introduction
Overview
What this Book includes
Is This Book for You
What Do You Need to Use This Book
How The Book Is Organized
Using Code Examples
Customer Support
Chapter 1: Overview of WPF Programming
New Features in WPF
XAML Basics
Why XAML Needed?
Creating XAML Files
Code-Behind Files
Your First WPF Program
Properties in XAML
Event Handlers in Code-Behind Files
Code-Only Example
XAML-Only Example
Chapter 2: 2D Transformations
Basics of Matrices and Transforms
Vectors and Points
Scaling
Reflection
Rotation
Translation
Homogeneous Coordinates
Translation in Homogeneous Coordinates
Scaling in Homegeneous Coordinates
Rotation in Homegeneous Coordinates
Combining Transforms
Vectors and Matrices in WPF
Vector Structure
Matrix Structure
Matrix Operations
Matrix Transforms
Creating Perpendicular Lines
Object Transformations in WPF
MatrixTransform Class
ScaleTransform Class
TranslateTransform Class
RotateTransform Class
SkewTransform Class
Composite Transforms
Chapter 3: WPF Graphics Basics in 2D
2D Coordinate Systems in WPF
Default Coordinates
Custom Coordinates
Custom Coordinates for 2D Charts
2D Viewport
Zooming and Panning
Resizable Canvas
Basic 2D Graphics Shapes
Lines
Rectangles and Ellipses
Polylines
Polygons
Paths and Geometries
Line, Rectangle, and Ellipse Geometries
GeometryGroup Class
CombinedGeometry Class
PathGeometry Class
Lines and Polylines
Arcs
Bezier Curves
Geometry and Mini-Language
Hit Testing
Custom Shapes
Star Class
Arrowline Class
Testing Custom Shapes
Chapter 4: Colors and Brushes
Colors
System Colors
Color Picker
Brushes
SolidColorBrush
LinearGradientBrush
RadialGradientBrush
DrawingBrush
Custom Colormap and Shading
Custom Colormap Brushes
testing Colormap Brushes
Color Shading
Testing Color Shading
Chapter 5: 2D Line Charts
Simple Line Charts
Creating Simple Line Charts
How It Works
Line Charts with Data Collection
Chart Style
Data Series
Data Collection
Creating Line Charts
Gridlines and Labels
Chart Style with Gridlines
Creating a Chart with Gridlines
Legends
Legend Class
Creating a Chart with Legend
Symbols
Defining Symbols
Creating a Chart with Symbols
Line Charts with Two Y Axes
Why We Need Two Y Axes
Chart Style with Two Y Axes
DataSeries and DataCollection with Two Y Axes
Creating a Chart with Two Y Axes
Chapter 6: Specialized 2D Charts
Bar Charts
DataSeries for Bar Charts
DataCollection for Bar Charts
Creating Simple Bar Charts
Creating Group Bar Charts
Creating Overlay Bar Charts.
Creating Stacked Bar Charts
Stair-Step Charts
DataSeries for Stair-Step Charts
DataCollection for Stair-Step Charts
Creating Stair-Step Charts
Stem Charts
DataCollection for Stem Charts
Creating Stem Charts
Error Bar Charts
DataSeries for Error Bar Charts
DataCollection for Error Bar Charts
Creating Error Bar Charts
Area Charts
DataSeries for Area Charts
DataCollection for Area Charts
Creating Area Charts
Polar Charts
Chart Style for Polar Charts
DataCollection for Polar Charts
Creating Polar Charts
Pie Charts
Pie Chart Style
Legend for Pie Charts
Creating Pie Charts
Chapter 7: Stock Charts
Static Stock Charts
Text File Reader
DataSeries and DataCollection for Stock Charts
Hi-Lo Stock Charts
Hi-Lo Open-Close Stock Charts
Candlestick Stock Charts
Moving Averages
Simple Moving Averages
Implementation
Creating SMA Curves
Weighted Moving Averages
Implementation
Creating WMA Curves
Exponential Moving Averages
Implementation
Creating EMA Curves
Using Yahoo Stock Charts in WPF
Connecting to Yahoo Stock Charts
Creating Yahoo Stock Charts in WPF
Chapter 8: Interactive 2D Charts
Automatic Tick Placement
Optimal Tick Spacing
Creating Charts with Automatic Ticks
Chart Panning with a Mouse
Chart Zooming with a Mouse
Chart Zooming with a Mouse Wheel
Retrieving Chart Data
Chapter 9: 2D Chart Controls
Line Chart Control
Defining Dependency Properties
Using the Line Chart Control
Creaing a Simple Line Chart
Creating Multiple Line Charts
Specialized 2D Chart Control
Bar Chart Control
Implementation
Creating Bar Charts
Creating Multiple Bar Charts
Stair-Step Chart Control
Implementation
Creating Stair-Step Charts
Stem Chart Control
Implementation
Creating Stem Charts
Error Bar Control
Implementation
Creating Error Bar Charts
Area Chart Control
Implementation
Creating Area Charts
Polar Chart Control
Implementation
Creating Polar Charts
Pie Chart Control
Implementation
Creating Pie Charts
Creating Multiple Charts
Chapter 10: Data Interpolations
Linear Interpolation
Algorithm
Implementation
Testing Linear Interpolation
Lagrange Interpolation
Algorithm
Implementation
Testing Lagrange Interpolation
Barycentric Interpolation
Algorithm
Implementation
Testing Barycentric Interpolation
Newton Divided-Difference Interpolation
Algorithm
Implementation
Testing Newton Divided-Difference Interpolation
Cubic Spline Interpolation
Algorithm
Implementation
Testing Cubic Spline Interpolation
Chapter 11: Curve Fitting
Linear Algebraic Equations
Gauss-Jordan Algorithm
Implementation
Least-Squares Fit
Straight-Line Fit
Implementation
Testing Straight-Line Fit
Linear Regression
Implementation
Testing Linear Regression
Polynomial Fit
Implementation
Testing Polynomial Fit
Weighted Linear Regression
Implementation
Exponential-Function Fit
Chapter 12: 3D Transformations
3D Matrices in WPF
3D Points and Vectors
Matrix3D Structure
Matrix3D Operations
Matrix3D Transforms
Rotation and Quaternion
Projections
Orthographic Projections
Multi-View Projections
Axonometric Projections
Perspective Projections
One-Point Perspective Projections
Two-Point Perspective Projections
Three-Point Perspective Projections
Perspective Projection Matrix
Views and Projections in WPF
View Transform
Perspective Projecion
View Frustum
Perspective Transform Matrix
Implementing Perspective Transforms
Testing Perspective Projections
Orthographic Projecion
Orthographic Transform Matrix
Implementing Orthographic Transforms
Testing Orthographic projections
Object Transforms in WPF
ScaleTransform3D class
TranslateTransform3D class
Rotate Transform3D class
MatrixTransform3D class
Combining Transforms
Chapter 13: WPF Graphics Basics in 3D
3D Graphics Basics
Viewpoint3D
3D Objects in WPF
Geometry and Mesh
GeometryModel3D and Surfaces
Illuminating the Scene
Camera Positions
Simple Triangle in 3D
Basic 3D Shapes
Coordinate Axes and Wireframe
Creating Cube
Creating Sphere
Creating Cylinder
Creating Cone
Creating Torus
Chapter 14: 3D Charts with the WPF 3D Engine
Simple Surfaces
Rectangular Meshes
SimpleSurface Class
Creating Simple Surfaces
Parametric Surfaces
ParametricSurface Class
Creating Parametric Surfaces
Helicoid Surface
Sphere Surface
Torus Surface
Quadric Surface
Extruded Surfaces
ExtrudedSurface Class
Creating Extruded Surfaces
Surfaces of Revolution
RotatedSurface Class
Creating Surfaces of Revolution
Surface Shading
SurfaceShading Class
Creating Shaded Surfaces
Chapter 15: 3D Charts without the WPF 3D Engine
3D Coordinate System
Azimuth and Elevation View
Creating a Cube
Chart Style in 3D
3D Coordinate Axes
Gridlines
Labels
Testing the Project
3D Line Charts
Implementation
Testing the Project
3D Surface Charts
Implementation
DataSeries Class
Chart Functions
DrawSurfaceChart Class
Mesh Charts
Curtain Charts
Waterfall Charts
Surface Charts
Chapter 16: Specialized 3D Charts
Implementation
2D Chart Style
Draw3DChart Class
Color Charts on the X-Y Plane
Implementation
Testing X-Y Color Charts
Contour Charts
Algorithm
Implementation
Testing Contour Charts
Combination Charts
X-Y Charts in 3D
Contour Charts in 3D
Filled Contour Charts
Mesh Contour Charts
Surface Contour Charts
Surface-Filled Contour Charts
3D Bar Charts
Implementation
Testing 3D Bar Charts
Index
Introduction
        Overview
        What This Book Includes
        Is This Book for You
        What Do You Need to Use This Book
        How This Book is Organized
        Using Code Examples
Overview
Welcome to Practical WPF Charts and Graphics. This book will provide all the tools you need to develop professional chart and graphics applications using the Windows Presentation Foundation (WPF) and C# based on the .NET framework. I hope this book will be useful for WPF and C# programmers of all skill levels.
We’ve all heard the saying “a picture’s worth a thousand words”. Charts and graphics play a very important role in every Windows application. They make data easier to understand, add interest to reports, and have wide applications in our daily life. In the scientific, engineering, and mathematics community, there is always a need to present data and results graphically. Microsoft’s .NET platform with C# and WPF is one of the few and best development tools available for providing the computational capabilities to both generate data as a simulation engine and display it in a variety of graphical representations based on WPF graphics capability.
As a C# programmer, you are probably already familiar with Windows Forms, the mature and full-featured development tool. Windows Forms is built on top of the .NET framework and uses the Windows API to create the visual appearance of standard user interface elements. It provides all kinds of tools for laying out windows, menus, dialogs, and controls. You can also develop graphics applications based on Windows Forms using the Graphical Device Interface (GDI+). However, creating a feature-rich graphics application using Windows Forms can be a difficult and tedious task. For example, Windows Forms provides no tools for creating three-dimensional (3D) graphics applications. Even a 3D point, the simplest of 3D graphics objects, must be defined first in a suitable 3D coordinate system before it can be used as a 3D graphics object.
WPF completely changes the landscape of graphics programming. At first, you might think that WPF just provides another way to create windows, menus, dialogs, and controls. However, WPF has much more to offer than any other Windows programming framework. It integrates three basic Windows elements – text, controls, and graphics – into a single programming model, and puts these three elements in the same element tree in the same manner.
Without WPF, developing a graphics application would involve using a number of different technologies, ranging from GDI/GDI+ for 2D graphics to Direct3D or OpenGL for 3D graphics. WPF, on the contrary, is designed as a single model for graphics application development, providing seamless integration between such services within an application. Similar constructs can be used for creating animations, data binding, and 3D models.
To take further advantage of new powerful graphics hardware technologies, WPF implements a vector-based graphics model. This allows for graphics to be scaled based on screen-specific resolution without the loss of image quality, something impossible to do with fixed-size raster graphics. In addition, WPF leverages Direct3D for vector-based rendering, and makes use of the graphics processing unit on any video card that implements DirectX in hardware.
With WPF, graphics elements can be easily integrated into any part of your user interface. For example, WPF provides 2D shape elements that can be involved in the user interface (UI) tree like other elements can. You are free to mix these shapes with any other kind of element, such as a button. The WPF 3D model is based on Direct3D technology and allows you to create a custom 3D shape library that can be reused in your projects. The main benefits that WPF offers in creating 3D graphics are its ease of use and its ability to integrate 3D content anywhere in applications.
As you may have already noticed, there are a plethora of WPF programming books currently available in bookstores. The vast majority of these books are general-purpose user guides and tutorials that explain the basics of WPF and how to use it in implementing simple WPF applications. To help users take full advantage of WPF graphics features, however, requires a book that provides an in-depth introduction specifically to WPF chart and graphics programming.
This book is written with the intention of providing you with a complete and comprehensive explanation of WPF chart and graphics capability, and pays special attention to creating various charts that can be directly used in real-world WPF applications. Much of this book contains original work based on my own programming experience when I was developing commercial Computer Aided Design (CAD) packages. Without WPF and the .NET framework, developing advanced charts and graphics is a difficult and time-consuming task. To add even simple charts or graphs to your applications, you might often have to waste effort creating a chart program, or buy commercial graphics and chart add-on packages.
Using third-party graphics and chart add-on products in your applications has several drawbacks, however:
- It isn’t cost effective – it might cost hundreds or thousands of dollars for a sophisticated graphics and chart package.
- Compatibility is an issue – these third-party graphics and chart add-on tools are usually provided as DLL or COM components, which often lead to unexpected interface exceptions and unstable operations.
- There is little flexibility – from users’ point of view, these packages appear to be black boxes because the source code is usually not provided, making it hard for users to add or modify any functionalities. You might find that these third-party products lack the special features you want to use in your applications, even though these products often provide an excess of extraneous functionalities that you will never use.
- The coding is inefficient – these third-party add-on tools are often very large packages that contain far more functionalities than you will ever need in your applications. Even for a simple program, the final release tends to be huge due to the use of third party add-ons. This is very inefficient for both coding management and distribution.
- License royalty is another issue – some third-party add-ons require not only the developing license, but also the distributed license royalty, resulting in an unnecessary increase in the development cost.
- Finally, maintenance is a problem – in most cases, third-party tools use a different programming language than the one you use in developing your applications, so you have to maintain the codes in an unmanaged manner.
Practical WPF Charts and Graphics provides everything you need to create your own advanced charts and graphics in your WPF applications. It shows you how to use C# and WPF to create a variety of graphics and charts that range from simple two-dimensional (2D) X-Y plots to complicated three-dimensional (3D) surface graphs. I will try my best to introduce you to C# and WPF chart and graphics programming in a simple way – simple enough to be easily followed by a beginner who has never had experience developing WPF chart and graphics applications before. You can learn from this book how to create a full range of 2D and 3D color graphics applications and how to use custom chart controls to create impressive graphic and chart effects without having to buy expensive third-party add-on products.
What this Book Includes
This book and its sample code listings, which are available for download from the Apress website or my own website, www.DrXuDotNet.com, provide you with:
- A complete, in-depth instruction on practical chart and graphics programming with C# and WPF. After reading this book and running the example programs, you will be able to add various sophisticated charts and graphics to your WPF applications.
- Ready-to-run example programs that allow you to explore the chart and graphics techniques described in the book. These examples can be used to better understand how the chart and graphics algorithms work. You can modify the code examples or add new features to them to form the basis of your own projects. Some of the example code listings provided in this book are already sophisticated chart and graphics packages that can be used directly in your own real-world WPF applications.
- Many classes in the sample code listings that you will find useful in your WPF chart and graphics programming. These classes include matrix manipulation, coordinate transformation, color maps, chart controls, and the other useful utility classes. You can extract these classes and plug them into your own applications.
Is This Book for You
You don’t have to be an experienced WPF developer or an expert to use this book. I designed this book to be useful to people of all levels of WPF programming experience. In fact, I believe that if you have some experience with the programming language C#, Windows Forms, HTML, and the .NET framework, you will be able to sit down in front of your computer, start up Microsoft Visual Studio 2008 and .NET 3.5, follow the examples provided in this book, and quickly become proficient with WPF chart and graphics programming. For those of you who are already experienced WPF developers, I believe this book has much to offer as well. There is a great deal of information in this book about chart and graphics programming not available in other WPF tutorial and reference books. In addition, most of the example programs in this book can be used directly in your own real-world application development. This book will provide you with a level of detail, explanation, instruction, and sample program code that will enable you to do just about anything WPF chart and graphics-related.
Perhaps you are a scientist, engineer, mathematician, student, or teacher instead of a professional programmer; nevertheless, this book is still a good bet for you. In fact, my own background is in theoretical physics, a field involving extensive numerical calculations as well as graphical representations of calculated data. I dedicated my effort to this field for many years, starting from undergraduate up to Ph.D. My first computer experience was with FORTRAN. Later on, I had programming experience with Basic, C, C++, and MATLAB. I still remember how hard it was in the early days to present computational results graphically. I often spent hours creating a publication-quality chart by hand, using a ruler, graph paper, and rub-off lettering. A year later, our group bought a chart and graphics package; however, I still needed to prepare my data in a proper format in order to process it with this package. During that time, I started paying attention to various development tools that could be used to create integrated applications. I tried to find an ideal development tool that would allow me not only to easily generate data (computation capability) but also represent data graphically (graphics and chart power). The C# and WPF development environment made it possible to develop such integrated applications. Ever since Microsoft .NET 1.0 came out, I have been in love with the C# language, and have been able to use this tool to successfully create powerful graphics and chart applications, including commercial CAD packages.
The majority of the example programs in this book can be used routinely by WPF developers and technical professionals. Throughout the book, I’ll emphasize the usefulness of WPF chart and graphics programming to real-world applications. If you closely follow the instructions presented in this book, you’ll be able to easily develop various practical WPF chart and graphics applications, from 2D graphics and charts to sophisticated 3D surface chart packages. At the same time, I won’t spend too much time discussing programming style, execution speed, and code optimization, because there is already a plethora of books out there that deal with these topics. Most of the example programs you’ll find in this book omit error handlings. This makes the code easier to understand by focusing only on the key concepts and practical applications.
What Do You Need to Use This Book
You’ll need no special equipment to make the best use of this book and understand the algorithms. To run and modify the sample programs, you’ll need a computer that is capable of running either Windows Vista or Windows XP. The software installed on your computer should include Visual Studio 2008 and .NET 3.5 standard edition or higher. If you have Visual Studio 2005 and .NET 3.0, you can also run most of the sample code with few modifications. Please remember, however, that this book is intended for Visual Studio 2008 and .NET 3.5, and that all of the example programs were created and tested on this platform, so it is best to run the sample code on the same platform.
How the Book Is Organized
This book is organized into sixteen chapters, each of which covers a different topic about WPF chart and graphics programming. The following summaries of each chapter should give you an overview of the book’s content:
Chapter 1, Overview of WPF Programming introduces the basics of WPF and reviews some of the general aspects of WPF programming, including the XAML files used to define user interfaces.
Chapter 2, 2D Transformations covers the mathematical basics of 2D graphics programming. 2D vectors, matrices, and transformations in the homogeneous coordinate system, including translation, scaling, reflection, and rotation, are discussed. These 2D matrices and transformations allow WPF applications to perform a wide variety of graphical operations on graphics objects in a simple and consistent manner.
Chapter 3, WPF Graphics Basics in 2D reviews some fundamental concepts of 2D graphics and the 2D drawing model in WPF. It introduces coordinate systems and basic 2D shapes.
Chapter 4, Colors and Brushes covers the color system and brushes that WPF uses to paint graphics objects. It introduces a variety of brushes and their transformations. You’ll learn how to create exotic visual effects using different brushes, including gradient and drawing brushes.
Chapter 5, 2D Line Charts contains instructions on how to create elementary 2D X-Y line charts. It introduces basic chart elements, including chart area, plot area, axes, title, labels, ticks, symbols, and legend. These basic chart elements are common in the other types of charts, as well.
Chapter 6, Specialized 2D Charts covers the specialized charts that are often found in commercial chart packages and spreadsheet applications. These specialized charts include bar charts, stair-step charts, stem charts, charts with error bars, pie charts, area charts, and polar charts.
Chapter 7, Stock Charts shows how to create a variety of stock charts in WPF, including the standard Hi-Lo-Open-Close stock charts, Candlestick stock charts, and moving averages. In addition, it also discusses embedding Yahoo stock charts into WPF applications.
Chapter 8, Interactive 2D Charts demonstrates how to implement interactive charts, which allow the user to interact with them by using a mouse to zoom, pan, and retrieve data from the chart.
Chapter 9, 2D Chart Controls shows how to put 2D chart applications into a custom user control, and how to use such a control in WPF applications.
Chapter 10, Data Interpolations explains the implementation of several interpolation methods, which can be used to construct new data points within the range of a discrete set of known data points.
Chapter 11, Curve Fitting explains a variety of curve fitting approaches that can be applied to data containing noise, usually due to measuring errors. Curve fitting tries to find the best fit to a set of given data.
Chapter 12, 3D Transformations extends the concepts described in Chapter 2 into the third dimension. It explains how to define 3D graphics objects and how to translate, scale, reflect, and rotate these 3D objects. It also describes transformation matrices that represent projection and transformations, which allow you to view 3D graphics objects on a 2D screen. You’ll also learn how WPF defines 3D vectors, matrices, and projections.
Chapter 13, WPF Graphics Basics in 3D explores the basics of 3D models in WPF. It introduces Viewport3D, the 3D geometry and the mesh model, lighting, camera, etc. You’ll also learn how to create basic 3D shapes directly in WPF.
Chapter 14, 3D Charts with WPF 3D Engine explains how to create various 3D surface charts, from simple surfaces to complex surfaces, using rectangular meshes and a variety of techniques, including parameterization, extrusion, and revolution. It also describes how to add lighting and shading effects to these surfaces.
Chapter 15, 3D Charts without WPF 3D Engine begins with a description of the coordinate system used in 3D charts and graphics, and shows you how to create 3D coordinate axes, tick marks, axis labels, and grid lines without using the WPF 3D engine. It then explains techniques of creating simple 3D surface charts.
Chapter 16, Specialized 3D Charts shows how to create a wide variety of 3D charts, including contour charts, 3D bar charts, and 3D combination charts. In creating these charts, a few specialized techniques, including Z-order, are used to manipulate the data displayed on your 2D computer screen.
Using Code Examples
You may use the code in this book in your own applications and documentation. You don’t need to contact the author or the publisher for permission unless you are reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book doesn’t require permission. Selling or distributing the example code listings does require permission. Incorporating a significant amount of example code from this book into your applications and documentation also requires permission. Integrating the example code from this book into commercial products is not allowed without written permission of the author and publisher.