Peter McGrattan’s Weblog

Silverlight, WCF, ASP.NET, AJAX, Graphics, RIA

Archive for the ‘Pie Chart’ Category

Silverlight 2 Pie Chart (Beta) Updated

Posted by petermcg on August 10, 2008

Edited on 20/October/2008 : Code download updated to support Silverlight 2 RTW

(Code download)

I recently returned from a break and had some time to add a few minor features to the pie chart beta.  If you have any ideas for features not included in this update, now would be a good time to let me know.

IsDoughnut Property and GapScale

One comment recently requested the ability to create a doughnut chart in Silverlight Beta 2.  This functionality has now been added and can be switched on or off via the IsDoughnut property.  The size of the hole in relation to the size of the pie-chart can also be controlled via the GapScale property:

<charts:PieChart x:Name="basicPie" Center="150.0, 150.0" Radius="100.0" IsDoughnut="True" GapScale="0.25"
                 Stroke="LightGray" StrokeThickness="2.0" FontSize="10">
    <charts:PieSegment Percentage="35" Foreground="Orange" />
    <charts:PieSegment Degrees="38" Foreground="Blue" />
    <charts:PieSegment Degrees="72" Foreground="Green" />
    <charts:PieSegment Degrees="101" Foreground="Red" />
    <charts:PieSegment Degrees="23" Foreground="Purple" />

This produces a chart as follows :

Basic Doughnut Pie Chart

When the IsDoughnut property is set to true, each segment is now comprised of four Points and two ArcSegments:

// Segment Geometry
double pieRadius = this.pieChart.Radius;
double gapRadius = pieRadius * ((this.pieChart.GapScale == 0.0) ? 0.35 : this.pieChart.GapScale);

Point A = GetCircumferencePoint(startAngle, pieRadius);
Point B = (this.pieChart.IsDoughnut) ? GetCircumferencePoint(startAngle, gapRadius) : this.pieChart.Center;
Point C = GetCircumferencePoint(endAngle, gapRadius);
Point D = GetCircumferencePoint(endAngle, pieRadius);

bool isReflexAngle = Math.Abs(endAngle - startAngle) > 180.0;

PathSegmentCollection segments = new PathSegmentCollection();
segments.Add(new LineSegment() { Point = B });

if (this.pieChart.IsDoughnut)
    segments.Add(new ArcSegment()
        Size = new Size(gapRadius, gapRadius),
        Point = C,
        SweepDirection = SweepDirection.Clockwise,
        IsLargeArc = isReflexAngle

segments.Add(new LineSegment() { Point = D });
segments.Add(new ArcSegment()
    Size = new Size(pieRadius, pieRadius),
    Point = A,
    SweepDirection = SweepDirection.Counterclockwise,
    IsLargeArc = isReflexAngle

Path segmentPath = new Path()
    StrokeLineJoin = PenLineJoin.Round,
    Stroke = this.pieChart.Stroke,
    StrokeThickness = this.pieChart.StrokeThickness,
    Data = new PathGeometry()
        Figures = new PathFigureCollection()
            new PathFigure()
                IsClosed = true,
                StartPoint = A,
                Segments = segments

The code above shows how a 2D Path (segmentPath) object is assembled for either a single pie-chart segment or a single doughnut segment.  A close look reveals four Point objects named A,B,C,D and two ArcSegment objects, one drawn in a Clockwise direction and the other in the default CounterClockwise direction.  The following image illustrates the location of these Points and the two ArcSegment objects when the IsDoughnut property is set to true.

Doughnut Arc Points

For a normal pie-chart segment (the default or when IsDoughnut is false) examination of the code above reveals that the Clockwise ArcSegment ending in point C is not required and that Point B becomes the center of the pie-chart.

Label Location, Color and Visibility

The labels can now be displayed inside or outside of the segments and their color and visibility can be controlled via the LabelLocation, LabelStroke and LabelVisibility properties respectively :

<charts:PieChart x:Name="linearPie" Center="150.0,150.0" Radius="100.0" Grid.Row="1"
                 Stroke="LightGray" StrokeThickness="2.0" FontSize="10" LabelLocation="Inside">
    <charts:PieSegment Degrees="45" Foreground="{StaticResource TwoColorLinearBrush}" />
    <charts:PieSegment Percentage="20" Foreground="{StaticResource TwoColorLinearBrush}" />
    <charts:PieSegment Degrees="225.0" Foreground="{StaticResource TwoColorLinearBrush}" />
    <charts:PieSegment Percentage="5" Foreground="{StaticResource TwoColorLinearBrush}" />

This produces the following chart :

Labels Inside

There have also been a few smaller updates in areas such as the MouseEnter animation and the addition of extra buttons to the demo to demonstrate changing values at runtime.  If you have an idea you would like to see in a future beta of this control, please let me know.


Posted in Pie Chart, Silverlight | Tagged: , , , , , , , | 6 Comments »

Samples Updated to Beta 2

Posted by petermcg on June 10, 2008

The API and documentation changes and the fact that Beta2 will not run applications that target Beta1 has obliged me to update links and all the samples previously posted on this blog such as the Pie Chart and Stock List Demo.  From this point on all posts will target Silverlight 2 Beta 2.

I started with a brand new Beta 2 solution when updating each sample to keep things clean.  The changes required to make the the new Pie Chart Solution work included updating the parameter list for the calls to the static Register method for the Dependency properties in the PieChart class now they require an instance of the PropertyMetadata class; a similar change to the Storyboard.SetTargetProperty method calls in PieLayoutManager that now require an instance of the PropertyPath class.  The need to add the MouseEnter animation Storyboard to the resources of the PieChart Canvas is removed thanks to the new support for the ability to create Storyboards in code that can animate parts of the render tree without having to be added to it.

The Stock List Demo Part 3 sample required the same changes for Storyboard.SetTargetProperty and also benefited from the fact that Storyboards created in code no longer have to be added to the Resources of a FrameworkElement for the stock highlight animations to work.  Other changes I ran into included that EventHandler<T> now requires T to inherit from EventArgs, the DataGrid’s AutoGenerateColumns is now true by default, displays itself using a smaller font by default and supports auto-sized columns.

The biggest change to the Stock List Demo project for Beta 2 was the new policy requirements around creating a Sockets server which have been implemented in the updated sample :

Console.WriteLine("Accepting Policy Requests...");

// Read policy file
byte[] policyBytes = File.ReadAllBytes("PolicyResponse.xml");

using (Socket client = policyListener.AcceptSocket())
    Console.WriteLine("Policy Request Accepted...");

    // Get policy request header
    byte[] buffer = new byte[1024];
    int bytesReceived = client.Receive(buffer);

    // Basic check of request header
    string header = Encoding.UTF8.GetString(buffer, 0, bytesReceived);

    if (header == "<policy-file-request/>")
        client.Send(policyBytes, 0, policyBytes.Length, SocketFlags.None);

Please download the latest version for a substantial demonstration of many areas of Silverlight development including Socket interaction that complies with the new policy changes in Silverlight 2 Beta 2.

As part of the upgrade I did run into this issue of not being able to discover a WCF web-service in the same solution after installing Beta 2 when creating the new solution for Stock List Demo 3.  The workaround at the end of the thread here solved the problem.

Please feel free to download the updated samples and as usual let me know any thoughts by adding a quick comment.

Posted in Pie Chart, Silverlight, Sockets, WCF | Tagged: , | 3 Comments »

Silverlight 2.0 Pie Chart (Beta)

Posted by petermcg on May 18, 2008

Edited on 26/June/2008 : Code download and Demos updated to support Silverlight 2 Beta 2

Edited on 20/October/2008 : Code download and Demos updated to support Silverlight 2 RTW

Basic Pie Chart Live Demo

Video Pie Chart Live Demo

Code Download for Silverlight 2 RTW

In an attempt to demonstrate some of the powerful 2D graphics support in Silverlight 2.0, I recently developed a re-usable implementation of a pie chart.  Having lately read some forum postings asking for a pie chart that works with Silverlight 2.0, I thought I’d publish what I’ve come up with.

Full source code and demos are available, the following headings show some of the main features as well as examples of pie charts you can create :

1. Basic Silverlight 2.0 Pie Chart :

Basic Pie Chart

2. Supports Radial Gradient, Linear Gradient and Video segments :

Linear Radial Video

3. How to create basic Pie Chart in XAML only :

<charts:PieChart x:Name="pieChart1" Center="150.0,150.0" Radius="100.0"
                 Stroke="LightGray" StrokeThickness="2.0" FontSize="10">
    <charts:PieSegment Percentage="35" Foreground="Orange" />
    <charts:PieSegment Degrees="38" Foreground="Blue" />
    <charts:PieSegment Degrees="72" Foreground="Green" />
    <charts:PieSegment Degrees="101" Foreground="Red" />
    <charts:PieSegment Degrees="23" Foreground="Purple" />

4. How to create basic Pie Chart in C# only :

PieChart pieChart1 = new PieChart()
    Center = new Point(150.0, 150.0),
    Radius = 100.0,
    Stroke = new SolidColorBrush(Colors.LightGray),
    StrokeThickness = 2.0,
    FontSize = 10.0,
    Segments = new PieSegmentList()
        new PieSegment() { Percentage = 35, Foreground = new SolidColorBrush(Colors.Orange) },
        new PieSegment() { Degrees = 38, Foreground = new SolidColorBrush(Colors.Blue) },
        new PieSegment() { Degrees = 72, Foreground = new SolidColorBrush(Colors.Green) },
        new PieSegment() { Degrees = 101, Foreground = new SolidColorBrush(Colors.Red) },
        new PieSegment() { Degrees = 23, Foreground = new SolidColorBrush(Colors.Purple) }

// XAML contains <Canvas x:Name="Canvas1" />

5. Specify segment size in Degrees or as a Percentage :

Percentage or Degrees - Highlighted

6. View changes as you type in Visual Studio 2008 Silverlight 2.0 Designer :

Silverlight 2.0 Designer

7. Implemented using Dependency Properties and ObservableCollection :

The chart will re-draw at runtime when you specify a new Segments Collection or modify the Center or Radius properties for example.

// Chart will redraw at new size and location
pieChart1.Radius = 150.0;

pieChart1.Center = new Point()
    X = 150.0,
    Y = 250.0

This provides support for databinding, animation of the chart.  View the demos and download the code for more information.

8. Efficient drawing and smooth mouse over animation :

Chart is drawn efficiently using framework classes in the System.Windows.Shapes and System.Windows.Media namespaces such as Path, LineSegment, ArcSegment and TranslateTransform.  MouseEnter animation is smooth, using a Storyboard in the System.Windows.Media.Animation namespace to animate the rendering of a TranslateTransform.

9. View running demos and download source :

Basic Pie Chart Live Demo

Video Pie Chart Live Demo

Code Download for Silverlight 2 RTW

Let me know any thoughts, requests, questions etc by posting a comment, it will help prioritise my todo list and I’m only too happy to hear if this is useful to you or not.

Posted in Pie Chart, Silverlight | Tagged: , , , | 39 Comments »