Posts Tagged ‘flex’

Embeded font

Saturday, December 19th, 2009

常用的Embeded font 寫法,從Adobe手冊抄來的:
重點是: 用同一個Font Family Name 但是Embed不同的Font Face, 這樣可處理大部分的字型問題,不然,常常會有字形粗體時跑回Arial, Tahoma 的情況。

@font-face {
        src:url("../assets/MyriadWebPro.ttf");
        fontFamily: myFont;
        advancedAntiAliasing: true;
     }

     @font-face {
        /* Note the different filename for boldface. */
        src:url("../assets/MyriadWebPro-Bold.ttf");
        fontFamily: myFont; /* Notice that this is the same alias. */
        fontWeight: bold;
        advancedAntiAliasing: true;
     }

     @font-face {
        /* Note the different filename for italic face. */
        src:url("../assets/MyriadWebPro-Italic.ttf");
        fontFamily: myFont; /* Notice that this is the same alias. */
        fontStyle: italic;
        advancedAntiAliasing: true;
     }

你也在寫Flex嗎? 那你可能要特別注意…

Tuesday, November 10th, 2009

本篇文章來自MAX2009的session:
How Not to code FLEX

演講者主要說明何謂壞程式碼(bad code),但也說壞程式碼不一定不好,只要你確定能盡快回來改正他。那何謂壞程式碼?

  • Container 元件的誤用:Container元件諸如Box, Canvas, Tile等等,他們的原本目的都是: 排列裡面的子元件。因此只要你不是拿來排版或甚至沒有給予它任何的子元件,就違背原本用意了。
    例子:

    <mx:TextInput/>
    <mx:VBox backgroundImage="blah.png" borderStyle="solid"/> <!-- 你看, 沒有小孩的容器元件-->
  • ListBase 元件的誤用: List, TileList, DataGrid 都是用來針對列表物件的選取、排序、renderer回收而生,因此,當你想要製作的元件並不需要這些功能,就不該採用List來處理。
  • local model binding: 避免直接將值給UI元件,盡量用local model binding來處理。(按:此方法還可避免元件初始化延遲所帶來的問題)
    ex:

    <mx:script>

      //這樣是不好的
      function test():void
      {
         myLabel.text = "hello";
      }

    </mx:script>
    <mx:Label id="myLabel"/>
    <mx:Script>
    //用local model binding.
    [Bindable]
    private var helloText:String = "hello";
    </mx:Script>
    <mx:Label id="myLabel" text="{helloText}"/>
  • 別把local view event 交由非常上層的元件處理。(按:這裡必須搭配cairngorm microframework 來解釋 )
    元件與元件之間的訊息傳遞,如果能在local就解決,便盡量不要拋到上層的command-frontcontroller 去處理然後又繞回來”原本的元件”。以後維護會很辛苦。
  • 不適當的容器元件使用方法:
    如果你發現你的容器元件裡面只有一個子元件(child),那可能有問題。
  • Two dots and you are out.
    兩個參照你就出局囉!

    如果你的程式碼需要進入非常多的子元件,那就有問題了。如下:

    var hey:String = myBox.thisBox.thatBox.rightLabel.text;

    這是一個本質上的問題,應該要封裝這些子元件,若其他元件需要存取裡面的值,應該要透過Event(帶資料出來) 來幫你。

  • 自以為的聰明寫法並不好。
    這種情況會發生在複雜的binding寫法,像是:

    <mx:Button id="btn" enabled="{ isCheck &amp;&amp; ( firstBtn.enabled &amp; !secondBtn.enabled) &amp;&amp; (thirdBtn.enabled|| feelGood) }"/>

    應該要用function 去處理這些binding 邏輯:

    <mx:Script>
    private function getEnabled( a:Boolea , b:Boolea , c:Boolean , d:Boolean , e:Boolean ):Boolean
    {
    //邏輯應該在這裡描述啦:
    return a && (b&&!c) &&(d||e);
    }
    </mx:Script>
    <mx:Button id="btn" enabled="{ getEnabled(isCheck,firstBtn.enabled,secondBtn.enabled,thirdBtn.enabled,feeGood) }"/>

一次展開Tree元件的所有節點(Expand All Children of Tree)

Sunday, March 22nd, 2009

展開一個Tree元件的所有節點的方法,有兩個階段:
1. 走訪所有節點
2. 如果是枝幹(branch)結點,就打開它( 有預設的方法可以使用, expandChildrenOf( node, open) )

要提醒的地方是,所有ListBase類型的元件,裡頭都有一個collectionChangeHandler的涵式,我們可以複寫他,讓每次資料重讀之後,就打開全部節點。
請見下方原始碼 :)

===
All ListBase-components handle collection with a collectionChangeHandler(event). All we have to do is override it by adding a expandAll() function. How will we do with this expandAll()? See following sample:

override protected function collectionChangeHandler(event:Event):void
{
    super.collectionChangeHandler( event );
   
    if( expandChildrenAfterReset )
    {
        if( CollectionEvent( event ).kind == CollectionEventKind.RESET )
        {
            expandAll();
        }
    }
}


public function expandAll():void
{
    if( collection )
    {
        var c:IViewCursor = collection.createCursor();
        var o:Object;
        while( !c.afterLast )
        {  
            o = c.current;
           
            if( dataDescriptor.isBranch( o ) )
                expandChildrenOf( o ,true );

            c.moveNext();
        }
    }
}

As you see, we just iterate all tree node, determining if it is a branch and then call the built-in expandChildreOf(node,open) method.

Table-like List (類似表格的List)

Monday, February 23rd, 2009

List displays scrollbar if containing too many items. What if we just need it expand as high as possible no matter how many items here? Some solutions are available :
If variableRowHeight is false, please assign explicit height as number of height multiplies rowHeight, as following code:

height = rowHeight * IList(dataProvider).length

Otherwise, if you get variableRowHeigh ture, there is a handy function for you:

measureHeightOfItems(0,0);

Please see List#measureHeightOfItems() for more information.


要讓List元件自己長到顯示所有資料的高度,像是表格一樣,有以下方法:
如果variableRowHeight 為 true , 表示每個資料物件所需欄高不同,可以用 List#measureHeightOfItems(index,count); 得出總高度。 反之,欄高都相同的情況,只要把欄高乘於資料數,得出總高就是了。

height = rowHeight * IList(dataProvider).length ;

消失的BarSeries標籤文字 - Missing Labels on Bar Series

Thursday, December 11th, 2008

[更新@2008.12.16]
關於更改Series上的label,修改InstanceCache宣告會更快更好:

/**
*To manipulate label instances on series, overridding the instanceCache object  is a better approach.
**/

labelCache = new InstanceCache( Label , labelContainer )
labelCache.property = { truncateToFit : false };

使用Bar Chart 的時候,有個現象:
當Bar上頭的標籤文字太長,以至於無法放進畫面中,BarChart 會清除掉裡面的文字內容:
label.text = “”; (請見BarChart.as line 662)
好在,它只是清掉renderData的cache,並非真正的dataProvider內容(如果是,就糟了),也因此,我們有機會把這些文字回覆,逼它無論如何都要顯示,方法很簡單,你可以自訂一個BarSeries,請見如下程式碼。走訪dataprovider,把值塞回去給Label 實體即可,但請確保文字框夠大,或是把truncateToFit改成false,這樣就不會被裁切掉了。

[English version]
A Bar-Chart renders several series where those labels show up. If you have read source of BarChart.as, you would aware of one thing: If by checking the TextField width against remaining space, there is no enough space to place the label , the label text will be eliminated. ( see source: BarChart.as Line 662 ) However, I think Adobe team might do too much here so that even if you set explicit textField width with a very large number, it won’t work. Fortunately, BarChart itself clear the renderCache instead of dataprovider so that we could recover the text of each label. Here is an example:

// extends BarSeries

//override updateDisplayList()
override protected function updateDisplayList( w:Number , h:Number )
{
super.udpateDisplayList( w , h );
//here we get all created *Label* instances
var labels:Array = labelCache.instances;
// cursor is a IViewCursor, iterating the dataprovider so that cursor#view is just dataprovider object.
var dataList:Array = IList( cursor.view ).toArray();
var len:int = labels.length;
//iterate all label instance, if the text is removed, re-assign it and validate as well.
//one more thing, the length of labels and dataprovider should be the same.
       var label:Label;
    for(var i:int = 0 ; i < len ; i++ )
    {
        label = Label( labels[i] );
        if( label )
        {
            label.truncateToFit = false; //optional
            label.width = Math.max(w,300); //optional
           
            if( label.text == "" && labelFunction != null )
            {
                var c:ChartItem = ChartItem( items[i] );
                c.item = v[i];
                var txt:String = this.labelFunction( c , this )
                label.text = txt;
            }
           
            label.validateNow();
        }  
}

Column Chart v.s. Bar Chart

Wednesday, October 1st, 2008

Well, it was confusing. I was thinking bar charts and column charts were doing the same thing. The distinct appearance of them is the direction of the “bar”. Actually, you could call columns “bars” if you want. Thus, I event didn’t get this critical idea that a bar chart CANNOT draw bars vertically. You know what? I struggled with this for hours. Finally I realized it.

So, please remember:
A Column Chart is showing number of columns vertically, which seems to “stand” on the horizontal axis.
A Bar Chart is showing number of bars horizontally, like a rotation column chart.
However, they are logically different.

測量文字框

Wednesday, September 17th, 2008

有個很方便的方法:

UIComponent#measureText( text:String ):TextLineMetrics

先看看官方說的:
Measures the specified text, assuming that it is displayed in a single-line UITextField using a UITextFormat determined by the styles of this UIComponent.

簡單來說,這個方法會根據你當下使用的文字樣式,測量一段文字的長寬高。舉例來說, “Taiwan” 這幾個字,在各種字體、字型大小設定下,顯示出來的結果當然不同(比如字體大小11pt時高度為21px; 14pt時高度為34px…) ,為了要得到正確的文字框數據,就可以運用該方法。
那麼,到底什麼時候會用到呢? 很多時候,在開發與TextField相關的自訂元件時,會大量地運用到,譬如 Button,裡頭的Label和icon要對齊,label的位置就利用了此方法測量出來,然後位移之。

看看原始碼,應該會常常看到這種寫法:
因為大寫W是最高的字, 小寫j是最低的字, 如此可以算出最大的文字框高度

measureText("Wj");

算出現有的文字框高度

measureText(textField.text);

UIComponent#measureText(text:String):TextLineMetrics

It is a very handy method for determining the bounds of a specific text. To illustrate, with different text format, the appearance of text must be different. In other words, the height, width and other values will be changed as well. Therefore, to make sure we get the correct and precise values of it, we can call this method to get a TextLineMetrics object, which provides all the properties. Given that object, we could update positions of components precisely.

For example, while the label of a button changes, we could measure it by

measureText(label)

or
to get a safe size of it, use following code:

measureText("Wj")

Here is a thing, the capital w and lowercase j are the latter with highest baseline and the lowest. That’s why Adobe developer often writes up code in this way.

FYI

Hide Chart Elements

Sunday, August 24th, 2008

First of all, a visual chart, generated via Flex-Charting framework, is constructed with many layers of elements. They are series(data) layer, axis layer, background elements and annotation elements. Besides, you are able to create your own chart elements by implementing IChartElement2 interface.

Here are some quick tips:

  • To kill the grid lines behind charts:
    backgroundElements=[]
  • To make the grid lines drawn with larger interval:
    GridLines#horizontalChangeCount = larger_number;
  • hide elements of axises
    AxisRenderer#showLabels = false;
    AxisRenderer#showLine = false;
    AxisRenderer#tickPlacements = "none";

用Filter Function作簡單線性圖Drill-Down

Monday, July 28th, 2008

首先,想像有一張線性圖(Line Chart),上頭的線是由許多資料點所構成。在Flex中,一旦對該資料及和作了過濾的動作,圖表會重繪。然後,Flex3的圖表都有支援selectedItems:Array的方法,以獲取你圈選的資料點,因此,我們可以藉由選取的資料點,得到一個範圍,利用範圍來過濾原資料集合,就可以做到類似Drill-Down的功能了。

這是範例(線性圖的drill down)
這是原始碼


Drill down into data in a line chart.

With Flex3 data visualization package, we are able to get the selectedItems by

ChartBase.selectionMode = "multiple";<br/>ChartBase.selectedItems

Therefore, it is handy to measure a range for filtering out our data. We have to know that every series in a chart contains a data provider. The data providers are ListCollectionView objects. So to filter out those objects will update the display of chart immediately. Those lines will be redrawn. You could see the line scaled just like drilling-down into it.

Here is a sample and source code.
Simple Drill Down into Line Chart
Source

提昇Flex圖表效能

Friday, July 25th, 2008

提昇Flex圖表元件 (Charting Components) 的效能,當你遇到圖表元件的繪製速度慢到想殺人的時候,建議你先從資料開始檢查,再看看圖表元件本身。

  • 如果可以,移除掉圖表效果,像是陰影
    ChartBase.seriesFilters=[]

  • 圖表的data-provider別餵太複雜的物件,尤其是很肥大的XML應該盡量避免,真的必要,可以作adapter物件來繪製之。
  • 當需要畫出很多條不同的資料線時,不要來一筆資料餵一次series (chartBase.series),能的話,讀完了再一次餵,因為一旦執行
    ChartBase.series = your_new_series_list

    會逼迫ChartBase重繪*所有的*的視覺元件,包含標籤、矩陣線、圖表線、軸線…等,很恐怖唷!尤其是你的資料又長到個不行時,老闆不開心、自己也難過。

  • 作線性圖( Line Chart )時,別輕易地變更線的樣式,尤其”form”, “miter”, “joint”這幾個,你可以看看官方的原始碼,對於這些屬性有非常不同的繪製演算法。用預設值吧,我相信Flex開發團隊已經先最佳化過了。
  • Gutter (gutter top, left, right, bottom) 能的話先給預設值,可以省下運算時間
  • 小心使用軸線的單位(unit),針對你的資料多寡,給予適當的單位值,如果你的資料有一千年,把單位切成秒數就不是個明智的作法。

以下是本文的英文版:

Enhance Flex Charting Components Performance

  • Clear the beautiful shadows or any other filters.
    ChartBase.seriesFilters=[]
  • Optimize your data objects to be rendered. Do not pass a bunch of huge, complex objects to the data-provider.
  • While building a line chart, do NOT change the lineStroke attributes such as “miter”, “joint” if not necessary. Flex Data-Visualization components has optimized the drawing performance to default renderers. To change these attributes may bring up a terrible risk.
  • You can remove the grid lines.
  • Set explicit gutter values while defining a chart base object.
  • If you have to render multiple series in a single chart, try to finish loading all data-providers before you assign series list to chart. Calling this method:
    ChartBase.series = your_list

    will force the chart to remove *ALL* chart elements( label, grid, axis, series items…) and re-create them. It is really time consuming to refresh the chart if re-assign the series objects again and again.

  • Set a lower quality of your flash movie( not available for AIR)
  • Mind your axis units. Be very careful while showing up a time-based data set. It is very possible to be the key to skew up your chart performance if the unit is set too small. Given an appropriate unit is highly recommended.