[Flex3.0 - Chart] AreaChart에 style 적용하고 categoryAxis 재 정의 하기

FLEX/FLEX 2010. 7. 12. 22:00

요즘 주로 하고 있는 chart에 대해서...ㅋㅋ

flex 기본 chart도 깔끔한 형태에 모습이 나온다 그런데 만들다보던 전체적인 chart에 대한 변화가 필요하다.
그래서 기본 chart에다가 style을 적용하고 categoryAxis를 재 정의 해 보았다.

categoryAxis를 재정의하는 이유는 여러 가지가 있겠지만 그중에서도 아마 많은 양의 데이터로 챠트를 구하다 보면
x축이 너무 지저분하게 보이는데 그것을 깔끔하게 보이기 위해서..ㅎㅎ (나만의 생각인가)

예제를 만들다 보니 새로만든 ReCategoryAxis.as파일이 너무 무식하게 작성되었다..ㅎㅎ
이건 필요한사람이 알아서.. 여기서는 어떻게 사용하는지에 대해서만..ㅋㅋ

-----------------------------------------------------------------------
Main.mxml

<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
 backgroundColor="#FFFFFF" backgroundAlpha="0" xmlns:local="*" creationComplete="initApp();">
 
 <mx:Script>
  <![CDATA[
   import mx.rpc.events.FaultEvent;
   import mx.rpc.events.ResultEvent;
   import mx.collections.ArrayCollection;
   import mx.controls.Alert;
   
   /// httpservice를 사용하여 리턴받은 데이터를 저장할곳....
   private var arcResult:ArrayCollection = new ArrayCollection();
   
   /// creationComplete에 직접 search.send()를 사용해도 되나 추후
   /// 추가 작업이나 데이터 초기화등 여러가지 호출될것이 있을수 있으므로 initApp()를 호출한다.
   private function initApp():void
   {
    search.send();
   }
   
   /// 정상적인 result event가 넘어 왔을때 처리하는 handler
   private function onResultHandler(event:ResultEvent):void
   {
    arcResult = new ArrayCollection();
    
    /// httpservice에서 리턴되는 데이터를 arcResult에 담는다. 구지 arrayCollection()으로 감쌓지 않아도 되나
    /// 보기 편하기 위해서...
    arcResult = ArrayCollection(event.result.data.value);
    
    /// 리턴되는 데이터가 있다면 실제 chart에 binding 시키자.
    if(arcResult && arcResult.length > 0)
    {
     chartBindData(); 
    }
   }
   
   /// httpservice가 fault event가 넘어올때 처리 handler
   private function onFaultHandler(event:FaultEvent):void
   {
    Alert.show("Fail Message=>" + event.fault.toString()); 
   }
   
   private function chartBindData():void
   {
    areaChtNew.dataProvider = arcResult;
    areaChtOrigin.dataProvider = arcResult;
    
    if(arcResult && arcResult.length)
     axisID.baseCount = Number(arcResult.length/10);
   }
   
  ]]>
 </mx:Script>
 
 <mx:Style>
  .areaChartStyle {
   horizontalAxisStyleName:chartStyle;
   verticalAxisStyleName:chartStyle;
  }
  
  .chartStyle {
   tickPlacement:outside;
   tickLength:4.0;
   fontFamily:Arial;
   fontSize:9;
   fontWeight:bold;
   color:#4e4e4e;
  }
  
  
 </mx:Style>

 <mx:HTTPService id="search" method="POST" url="http://www.riamx.com/blog/20090511/data.php"
  result="onResultHandler(event);" fault="onFaultHandler(event);" />
 
 <mx:VBox width="600" height="300" borderColor="#cbcbcb" borderStyle="solid" horizontalAlign="center">
  <mx:Label text="Style 적용 차트" fontSize="11" color="0xe20000"/>
  <mx:AreaChart id="areaChtNew" width="100%" height="100%" paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10"
   styleName="areaChartStyle" showDataTips="true">

   <mx:horizontalAxis>
    <local:ReCategoryAxis id="axisID" categoryField="xValue"/>
   </mx:horizontalAxis>
   
   <mx:series>
    <mx:AreaSeries yField="yValue">
     <mx:areaFill>
      <mx:LinearGradient angle="90">
       <mx:entries>
        <mx:GradientEntry color="0x183771"/>
        <mx:GradientEntry color="0x8fabdf"/>
       </mx:entries>
      </mx:LinearGradient>
     </mx:areaFill>
    </mx:AreaSeries> 
   </mx:series>
   
   <mx:backgroundElements>
    <mx:HBox width="100%" height="100%"  borderStyle="solid" borderColor="#dedddd" backgroundColor="0xffffff" borderThickness="1"/> 
    
    <mx:GridLines direction="horizontal">
     <mx:horizontalStroke>
      <mx:Stroke color="#efefef"/>
     </mx:horizontalStroke>
    </mx:GridLines>
   </mx:backgroundElements>
      
  </mx:AreaChart>
 </mx:VBox>
 
 <mx:VBox width="600" height="300" borderColor="#cbcbcb" borderStyle="solid" horizontalAlign="center">
  <mx:Label text="Style 미적용 차트" fontSize="11" color="0xe20000" />
  <mx:AreaChart id="areaChtOrigin" width="100%" height="100%" paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10">
  
   <mx:horizontalAxis>
    <mx:CategoryAxis categoryField="xValue"/>
   </mx:horizontalAxis>
   
   <mx:series>
    <mx:AreaSeries yField="yValue" />
   </mx:series>   
   
  </mx:AreaChart>
 </mx:VBox>

</mx:Application>

------------------------------
ReCategoryAxis.as

package
{
 import mx.charts.AxisLabel;
 import mx.charts.CategoryAxis;
 import mx.charts.chartClasses.AxisLabelSet;
 
 public class ReCategoryAxis extends CategoryAxis
 {
  [Bindable]
  public var baseCount:int;
  
  public override function getLabelEstimate():AxisLabelSet
  {
   var preResult:AxisLabelSet = super.getLabelEstimate();
   var labels:Array = [];
   var ticks:Array = [];
   var oldLabelIndex:int = 0;
   var newLabelIndex:int = 0;
   
   
   for(oldLabelIndex = 0; oldLabelIndex < preResult.labels.length; oldLabelIndex++)
   {
    var label:AxisLabel = preResult.labels[oldLabelIndex];
    var tempValue:int = new int(label.text);
    
    if(oldLabelIndex == 0 || (tempValue%baseCount) == 0)
    {
     labels[newLabelIndex] = label;
     ticks[newLabelIndex] = preResult.ticks[oldLabelIndex];
     newLabelIndex++;
    }
   }
   
   var result:AxisLabelSet = new AxisLabelSet();
   result.labels = labels;
   result.minorTicks = null;
   result.ticks = ticks;
   result.accurate = true;
   return result;
  }
 }
}





위와 같이 chart에 style 적용한것과 적용하지 않을것을 보면 왜 style을 적용해야되는지 잘 비교된다.
기본적인 차트 색은 오랜지색인데 여기에다가 gradient를 적용하여 2가지 색을 넣어보았다.

그리고 x축을 보면 데이터를 100개 binding 했더니 알아보지도 못하게 나오는데 이것은 categoryAxis를
재정의 하여 10단위 일때만 나타나게 변경했다.
: