Rotating a Flex PieChart control when a user clicks on an item

The following example shows how you can rotate a PieChart in Flex when the user clicks on an item. This allows you to make sure that the clicked item always appears at 0 degrees rotation (off to the right).

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/11/07/rotating-a-flex-piechart-control-when-a-user-clicks-on-an-item/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.charts.series.items.PieSeriesItem;
            import mx.charts.events.ChartItemEvent;

            private function pieChart_itemClick(evt:ChartItemEvent):void {
                var item:PieSeriesItem = evt.hitData.chartItem as PieSeriesItem;
                var degrees:Number = radiansToDegrees(item.startAngle);
                var arr:Array = [];
                if (checkBox.selected) {
                    arr[item.index] = 0.2;
                }
                pieSeries.perWedgeExplodeRadius = arr;
                pieSeries.startAngle -= degrees;
            }

            private function radiansToDegrees(radians:Number):Number {
                return radians * (180 / Math.PI);
            }
        ]]>
    </mx:Script>

    <mx:XML id="dp">
        <products>
            <product label="Product 1" data="3" />
            <product label="Product 2" data="1" />
            <product label="Product 3" data="4" />
            <product label="Product 4" data="1" />
            <product label="Product 5" data="5" />
            <product label="Product 6" data="9" />
        </products>
    </mx:XML>

    <mx:ApplicationControlBar dock="true">
        <mx:CheckBox id="checkBox"
                label="Use perWedgeExplodeRadius:"
                labelPlacement="left"
                selected="true" />
    </mx:ApplicationControlBar>

    <mx:PieChart id="pieChart"
            dataProvider="{dp.product}"
            itemClick="pieChart_itemClick(event);"
            height="100%"
            width="100%">
        <mx:series>
            <mx:PieSeries id="pieSeries"
                    field="@data"
                    labelPosition="callout">
                <mx:stroke>
                    <mx:Stroke color="black" weight="0" />
                </mx:stroke>
                <mx:filters>
                    <mx:Array />
                </mx:filters>
            </mx:PieSeries>
        </mx:series>
    </mx:PieChart>

</mx:Application>

View source is enabled in the following example.

0 thoughts on “Rotating a Flex PieChart control when a user clicks on an item