According to the requirement, a bunch of string lengths are searched online.Algorithm, Which is summarized and analyzed below.
AnalysisCodeAs follows:
<FX: SCRIPT>
<! [CDATA [
Import Flash. utils. bytearray;
// Interface Initialization
Private Function Init (): void {
Trace ("Length:" + lB. Text. Length );
// The width of a byte is about 7.5px, and the number of bytes calculated below is * 7.5
// Encoding conversion
VaR Bytearr: bytearray = new bytearray ();
Bytearr. writemultibyte (Lb. Text, "GBK ");
VaR Bytelength: Int = bytearr. length;
Trace ("Change GBK:" + bytelength + "Length:" + bytelength * 7.5 );
// The regular expression is used to replace one Chinese character with two "X" characters to read the true length of bytes.
VaR N: Int = LB. Text. Replace (/[^ \ x00-\ xFF]/g, "XX"). length;
Trace ("RegEx:" + N + "Length:" + N * 7.5 );
// Special characters such as uppercase and lowercase letters, operators, and percent signs make the width of the calculation result unsatisfactory.
// For example, the font width and font size also change the length.
// Finally, textmetrics is used to calculate the width of a text.
VaR Textmetrics: Flash. Text. textlinemetrics = LB. measuretext (Lb. Text );
Trace ("textmetrics width:" + textmetrics. width );
}
]>
</FX: SCRIPT>
<S: Label id = "LB" text = "ABCD 1234 1234" fontsize = "16"/>
The information displayed on the initialization page is as follows:
Length: 12
Change GBK: 16 length: 120
RegEx: 16 length: 120
Textmetrics width: 142
Method call
Import Flash. Text. textlinemetrics;
Import Spark. components. label;
Private Function Getlabelwidth (value: String ): Int {
VaR LB: Label = new label (); lb. stylename = "lbstyle"; // you can add a style if. lbstyle {fontsize: 16 ;}
LB. regeneratestylecache ( False );
VaR Textmetrics: textlinemetrics = LB. measuretext (value );
Return Textmetrics. Width + 10;
}