AS3 动态加载字体

 

AS3 动态加载字体 ( AS3 Runtime Font Loading )

 

 

 

1. 为什么要动态加载字体

比如你需要让用户自定义 textField 的字体.

如果这些字体都 Embed 到项目中去的话, 就会大大增加项目Size.

并且, 每次您更改字体的时候都要重新编译.

 

 

2. 常用方法

第一步, 创建一个独立于项目之外的 font.swf. 这个swf即为字体文件. 内容如下:

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package {
 
    import flash.display.Sprite;
 
    public class FontLibrary extends Sprite {
 
        [Embed(systemFont='Bank Gothic', fontName='emBank Gothic', mimeType='application/x-font')]
        public static var BankGothicFont:Class;
 
    }
 
}
 
    

 

第二步, 在主项目中这样使用动态加载的字体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loader.load(new URLRequest("fontlibrary.swf"));
 
private function completeHandler(event:Event):void {
    var FontLibrary:Class = event.target.applicationDomain.getDefinition("FontLibrary") as Class;
    Font.registerFont(FontLibrary.BankGothicFont);
    var tf:TextField = new TextField();
    tf.defaultTextFormat = new TextFormat("emBank Gothic", 12, 0);
    tf.embedFonts = true;
    tf.rotation = 15; // to demonstrate the embed worked
    tf.text = "blah blah blahnblah blah blahnblah blah blah ";
    addChild(tf);
}
 
 
    

 

 

 

3. 进阶方法

上面的做法, 即 把 “Embed 字体” 的操作从主项目嫁祸到辅助项目 font.swf 文件中去.

基本解决了我们动态加载字体的需求.

但是作为 程序员, 一件事情不弄舒坦是停不下来的. 上面的方法存在什么问题呢:

  1. 我们需要为每个字体文件单独生成一个 swf. 如果要有10个字体, 我就要处理10次. 这件事挺起来一点都不 Geek, 你能忍么? 反正我是不能忍
  2. 如果我们需要精简字体, 利用上一篇博文( Flash精简字体打包成SWF )中的方法打包成 精简的 swf. 为什么一个字体文件需要两个 swf 来浪费我的编译时间?

好了. 抱怨结束. 下面开始正文.

 

3.1 原理:

1. SWF文件是由一个文件头,以及一系列的标签组成的。标签类型有两种:定义型标签和控制型标签。( SWF文件格式解析请摸我 )

2. 咱们的字体在SWF中会对应一个定义型标签. 每个定义型标签有一个类型字段, 字体标签对应的类型为: 10 . ( SWF文件格式详解见官方文档: SWF File Format Specification )

image

官方文档中 DefineFont 标签的 简要信息

3. 理论上, 咱们加载完一个 SWF 文件之后, 只要挨家挨户找 Tag 类型为 10 的Tag. 就能把所有的 字体信息提取出来.

4. 但是提取出来之后, 我们还必须按照 SWF Player 可以识别的格式来组织起来, SWF Player 才能认识.

 

3.2 实现

上面的原理讲得头头是道, 第4步的重新组织是一个非常复杂精细并需要阅读大量文档的任务.

这方面, 咱们头顶上的俄国人比较突出. 下面就是一位 俄罗斯 Geeker 带来的 FontLoader. ( 请关注这位大拿的博客 )

优点:

  1. 能把 SWF 文件中的所有字体都提取出来, 为我所用.
  2. 与主项目几乎无干扰
  3. 无需其他类, 总共就一个文件 FontLoader.as . 不会增加主项目大小
  4. 无需代码共享库
  5. … ( 非常 Geek, 非常 方便… )

用例:

1
2
3
4
5
6
7
var url:String = 'aaaa.swf';
var loader:FontLoader = new FontLoader( new URLRequest( url ) );
loader.addEventListener( Event.COMPLETE, onFontLoaded );
private static function onFontLoaded( e:Event ):void
{
    //字体已经注册成功, 做你其它的事情
}

更详细的用法请下载 FontLoader.as ( 点击下载 ) 查看源代码吧

想了想, 还是把源码贴上来吧. 更直观一些:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
/**
 * FontLoader 2.3 by Denis Kolyako. June 13, 2008. Last update: January 20, 2011.
 * Visit http://etcs.ru for documentation, updates and more free code.
 *
 * You may distribute this class freely, provided it is not modified in any way (including
 * removing this header or changing the package path).
 *
 *
 * Please contact etc[at]mail.ru prior to distributing modified versions of this class.
 */
/**
 * The FontLoader class lets you load any swf movie (ver. 6 or later), which contains embedded fonts (CFF too) to use these fonts in your application.
 */
package ru.etcs.utils {
    import flash.display.Loader;
    import flash.events.ErrorEvent;
    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.events.HTTPStatusEvent;
    import flash.events.IOErrorEvent;
    import flash.events.ProgressEvent;
    import flash.events.SecurityErrorEvent;
    import flash.net.URLLoader;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequest;
    import flash.system.ApplicationDomain;
    import flash.system.LoaderContext;
    import flash.text.Font;
    import flash.utils.ByteArray;
    import flash.utils.Endian;
     
    [Event("complete", type="flash.events.Event")]
    [Event("open", type="flash.events.Event")]
    [Event("ioError", type="flash.events.IOErrorEvent")]
    [Event("verifyError", type="flash.events.IOErrorEvent")]
    [Event("httpStatus", type="flash.events.HTTPStatusEvent")]
    [Event("progress", type="flash.events.ProgressEvent")]
    [Event("securityError", type="flash.events.SecurityErrorEvent")]
    /**
     * FontLoader class
     *
     * @author                    etc
     * @version                    2.3
     * @playerversion            Flash 9
     * @langversion                3.0
     */
    public class FontLoader extends EventDispatcher {
         
        /**
         * @private
         */
        private static const SWF_HEADER:ByteArray = new ByteArray();
         
        /**
         * @private
         */
        private static const CLASS_CODE:ByteArray = new ByteArray();
         
        /**
         * @private
         */
        private static const CLASS_NAME_PREFIX:String = 'Font$';
         
        /**
         * @private
         */
        private static const TAG_DO_ABC:uint = ((72 << 6) | 0x3F);
         
        /**
         * @private
         */
        private static const TAG_SYMBOL_CLASS:uint = ((76 << 6) | 0x3f);
         
        /**
         * @private
         */
        private static var _initialized:Boolean = false;
         
        /**
         * @private
         */
        private static function init():void {
            if (FontLoader._initialized) return;
            var ba:SWFByteArray = new SWFByteArray();
            ba.writeBytesFromString(
                '7800055F00000FA000000C01004411080000004302FFFFFFBF150B0000000100466F6E744C69620000' +
                'BF1461020000010000000010002E00000000191272752E657463732E7574696C733A466F6E7400432F' +
                '55736572732F6574632F4465736B746F702F50726F6A656374732F466F6E744C6F616465724C69622F' +
                '7372633B72752F657463732F7574696C733B466F6E742E61731772752E657463732E7574696C733A46' +
                '6F6E742F466F6E74175B4F626A65637420466F6E7420666F6E744E616D653D2208666F6E744E616D65' +
                '0D2220666F6E745374796C653D2209666F6E745374796C650C2220666F6E74547970653D2208666F6E' +
                '745479706502225D1B72752E657463732E7574696C733A466F6E742F746F537472696E670653747269' +
                '6E6708746F537472696E67175F5F676F5F746F5F646566696E6974696F6E5F68656C700466696C6543' +
                '2F55736572732F6574632F4465736B746F702F50726F6A656374732F466F6E744C6F616465724C6962' +
                '2F7372632F72752F657463732F7574696C732F466F6E742E617303706F73033636380D72752E657463' +
                '732E7574696C7304466F6E740A666C6173682E74657874064F626A6563740335373006050116021614' +
                '161618010201030A07020607020807020A07020D07020E070315070415091501070217040000020000' +
                '00040000040C0000000200020F02101211130F02101211180106070905000101054100020100000001' +
                '030106440000010104000101040503D03047000001010105060EF103F018D030F019D04900F01A4700' +
                '00020201050620F103F01CD0302C05F01DD00401A02C07A0D00402A02C09A0D00403A02C0BA0480000' +
                '030201010421D030F103F0165D085D096609305D076607305D07660758001D1D6806F103F00B470000'
            ); // Magic bytes :-)
            ba.position = 0;
            ba.readBytes(FontLoader.SWF_HEADER);
            ba.length = 0;
            ba.writeBytesFromString(
                '392F55736572732F6574632F4465736B746F702F50726F6A656374732F466F6E744C6F616465724C69' +
                '622F7372633B3B466F6E743030302E61730568656C6C6F2B48656C6C6F2C20776F726C642120497320' +
                '616E79626F647920686572653F2057686F27732074686572653F0F466F6E743030302F466F6E743030' +
                '300D72752E657463732E7574696C7304466F6E74064F626A6563740A666C6173682E74657874175F5F' +
                '676F5F746F5F646566696E6974696F6E5F68656C700466696C65382F55736572732F6574632F446573' +
                '6B746F702F50726F6A656374732F466F6E744C6F616465724C69622F7372632F466F6E743030302E61' +
                '7303706F73023534060501160216071801160A00050702010703080702090705080300000200000006' +
                '0000000200010B020C0E0D0F0101020904000100000001020101440100010003000101050603D03047' +
                '0000010102060719F103F006D030EF01040008F007D049002C05F00885D5F009470000020201010527' +
                'D030F103F00465005D036603305D046604305D026602305D02660258001D1D1D6801F103F002470000'
            ); // Another magic bytes :-)
            ba.position = 0;
            ba.readBytes(FontLoader.CLASS_CODE);
            ba.length = 0;
            FontLoader._initialized = true;
        }
         
        /**
         * Creates a new FontLoader object. If you pass a valid URLRequest object to the FontLoader constructor,
         * the constructor automatically calls the load() function.
         * If you do not pass a valid URLRequest object to the FontLoader constructor,
         * you must call the load() function or the stream will not load.
         *
         * @param request (default = null) — The URL that points to an external SWF file.
         * @param autoRegister — Register loaded fonts automatically.
         */
        public function FontLoader(request:URLRequest = null, autoRegister:Boolean = true) {
            super();
            FontLoader.init();
            this._loader.dataFormat = URLLoaderDataFormat.BINARY;
            this._loader.addEventListener(Event.COMPLETE,                         this.handler_complete);
            this._loader.addEventListener(Event.OPEN,                             super.dispatchEvent);
            this._loader.addEventListener(HTTPStatusEvent.HTTP_STATUS,             super.dispatchEvent);
            this._loader.addEventListener(IOErrorEvent.IO_ERROR,                 super.dispatchEvent);
            this._loader.addEventListener(ProgressEvent.PROGRESS,                 super.dispatchEvent);
            this._loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,     super.dispatchEvent);
            if (request) this.load(request, autoRegister);
        }
         
        /**
         * @private
         */
        private const _loader:URLLoader = new URLLoader();
         
        /**
         * @private
         */
        private var _bytes:ByteArray;
         
        /**
         * @private
         */
        private var _libLoader:Loader;
         
        /**
         * @private
         */
        private var _fontCount:uint;
         
        /**
         * @private
         */
        private var _embeddedID:uint;
         
        /**
         * @private
         */
        private var _autoRegister:Boolean = true;
         
        /**
         * Sets automatic font registration.
         */
        public function set autoRegister(value:Boolean):void {
            if (this._autoRegister == value) return;
            this._autoRegister = value;
            if (value) this.registerFonts();
        }
         
        public function get autoRegister():Boolean {
            return this._autoRegister;
        }
         
        public function get bytesLoaded():uint {
            return this._loader.bytesLoaded;
        }
         
        public function get bytesTotal():uint {
            return this._loader.bytesTotal;
        }
         
        /**
         * @private
         */
        private const _fonts:Array = new Array();
         
        /**
         * Returns an array of font classes, which you can use to register any extracted font.
         */
        public function get fonts():Array {
            return this._fonts.concat();
        }
         
        /**
         * Initiates loading of an external SWF file from the specified URL. You can load another swf file, when previous operation completed (or stream closed by user).
         *
         * @param request:URLRequest — A URLRequest object specifying the URL to download. If the value of this parameter or the URLRequest.url property of the URLRequest object passed are null, Flash Player throws a null pointer error. 
         * @param autoRegister — Register loaded fonts automatically.
         *
         * @event complete:Event — Dispatched after data has loaded and parsed successfully.
         * @event httpStatus:HTTPStatusEvent — If access is by HTTP, and the current Flash Player environment supports obtaining status codes, you may receive these events in addition to any complete or error event.
         * @event ioError:IOErrorEvent — The load operation could not be completed.
         * @event verifyError:IOErrorEvent — Dispatched when a parse operation fails (data has incorrect format).
         * @event open:Event — Dispatched when a load operation starts.
         * @event securityError:SecurityErrorEvent — A load operation attempted to retrieve data from a server outside the caller's security sandbox. This may be worked around using a policy file on the server.
         */
        public function load(request:URLRequest, autoRegister:Boolean = true):void {
            this.close();
            this._fonts.length = 0;
            this._fontCount = 0;
            this._autoRegister = autoRegister;
            this._loader.load(request);
        }
         
        /**
         * Loads from binary data stored in a ByteArray object.
         *
         * @param bytes:URLRequest — A ByteArray object. The specified ByteArray must contain valid SWF file.
         * @param autoRegister — Register loaded fonts automatically.
         *
         * @event complete:Event — Dispatched after data has loaded and parsed successfully.
         * @event httpStatus:HTTPStatusEvent — If access is by HTTP, and the current Flash Player environment supports obtaining status codes, you may receive these events in addition to any complete or error event.
         * @event ioError:IOErrorEvent — The load operation could not be completed.
         * @event verifyError:IOErrorEvent — Dispatched when a parse operation fails (data has incorrect format).
         * @event open:Event — Dispatched when a load operation starts.
         * @event securityError:SecurityErrorEvent — A load operation attempted to retrieve data from a server outside the caller's security sandbox. This may be worked around using a policy file on the server.
         */
        public function loadBytes(bytes:ByteArray, autoRegister:Boolean = true):void {
            this.close();
            this._fonts.length = 0;
            this._fontCount = 0;
            this._autoRegister = autoRegister;
            this.analyze(bytes, true);
        }
         
        /**
         * Closes the stream, causing any download of data to cease.
         */
        public function close():void {
            try {
                this._loader.close();
            } catch (error:Error) {}
             
            if (this._libLoader) {
                this._libLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, this.handler_libComplete);
                 
                try {
                    this._libLoader.close();
                } catch (error:Error) {}
                 
                try {
                    this._libLoader.unload();
                } catch (error:Error) {}
                 
                this._libLoader = null;
            }
        }
         
        /**
         * Registers all loaded fonts.
         */       
        public function registerFonts():void {
            for each (var font:Font in this._fonts) {
                Font.registerFont((font as Object).constructor);
            }
        }
         
        /**
         * @private
         */
        private function analyze(bytes:ByteArray, delayed:Boolean = false):void {
            var o:Object;
            var stringID:String;
            var id:uint;
            var tempData:ByteArray;
            var fontSWF:ByteArray;
            var context:LoaderContext;
            var data:ByteArray;
             
            try {
                data = new SWFByteArray(bytes);
            } catch (error:Error) {
                if (delayed) {
                    this._libLoader = new Loader();
                    this._libLoader.addEventListener(Event.ENTER_FRAME, this.handler_delayedVerifyError);
                } else {
                    this.close();
                    super.dispatchEvent(new IOErrorEvent(IOErrorEvent.VERIFY_ERROR));
                }
                 
                return;
            }
             
            var fontData:Object = new Object();
            var classCodeLength:uint = FontLoader.CLASS_CODE.length;
            this._embeddedID = 0;
             
            this.processSWF(data, fontData);
             
            tempData = new ByteArray();
            tempData.endian = Endian.LITTLE_ENDIAN;
            tempData.writeBytes(FontLoader.SWF_HEADER);
            id = 0;
             
            for (o in fontData) {
                data = fontData[o] as ByteArray;
                 
                if (data) {
                    stringID = id.toString();
                    while (stringID.length < 3) stringID = '0' + stringID;
                    stringID = FontLoader.CLASS_NAME_PREFIX + stringID;
                    tempData.writeShort(FontLoader.TAG_DO_ABC);
                    tempData.writeUnsignedInt(10 + stringID.length + classCodeLength);
                    tempData.writeUnsignedInt(0x002E0010);
                    tempData.writeUnsignedInt(0x10000000);
                    tempData.writeByte(stringID.length);
                    tempData.writeUTFBytes(stringID);
                    tempData.writeByte(0);
                    tempData.writeBytes(FontLoader.CLASS_CODE);
                    tempData.writeBytes(data);
                    tempData.writeShort(FontLoader.TAG_SYMBOL_CLASS);
                    tempData.writeUnsignedInt(5 + stringID.length);
                    tempData.writeShort(1);
                    tempData.writeShort(o as uint);
                    tempData.writeUTFBytes(stringID);
                    tempData.writeByte(0);
                    id++;
                }
            }
             
            this._fontCount = id;
             
            if (this._fontCount) {
                tempData.writeUnsignedInt(0x00000040);
                fontSWF = new ByteArray();
                fontSWF.endian = Endian.LITTLE_ENDIAN;
                fontSWF.writeUTFBytes('FWS');
                fontSWF.writeByte(9);
                fontSWF.writeUnsignedInt(tempData.length + 8);
                fontSWF.writeBytes(tempData);
                this._libLoader = new Loader();
                this._libLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.handler_libComplete);
                context = new LoaderContext();
                 
                if ('allowLoadBytesCodeExecution' in context) { // AIR compatibility
                    context['allowLoadBytesCodeExecution'] = true;
                }
                 
                this._libLoader.loadBytes(fontSWF, context);
            } else {
                if (delayed) {
                    this._libLoader = new Loader();
                    this._libLoader.addEventListener(Event.ENTER_FRAME, this.handler_delayedComplete);
                } else {
                    this.close();
                    super.dispatchEvent(new Event(Event.COMPLETE));
                }
            }           
        }
         
        /**
         * @private
         */
        private function processSWF(data:ByteArray, fontData:Object, startFontID:uint = 0):void {
            var fontID:uint;
            var id:uint;
            var tag:uint
            var length:uint;
            var pos:Number;
            var tempData:ByteArray;
             
            while (data.bytesAvailable) {
                tag = data.readUnsignedShort();
                id = tag >> 6;
                length = ((tag & 0x3F) == 0x3F) ? data.readUnsignedInt() : (tag & 0x3F);
                pos = data.position;
                 
                switch (id) {
                    case 13:
                    case 48:
                    case 62:
                    case 73:
                    case 75:
                    case 88:
                    case 91:
                        fontID = data.readUnsignedShort() + startFontID;
                        tempData = fontData[fontID] as ByteArray;
                         
                        if (!tempData) {
                            tempData = new ByteArray();
                            tempData.endian = Endian.LITTLE_ENDIAN;
                            fontData[fontID] = tempData;
                        }
                         
                        if ((tag & 0x3F) == 0x3F) {
                            tempData.writeShort((id << 6) | 0x3F);
                            tempData.writeUnsignedInt(length);
                        } else {
                            tempData.writeShort((id << 6) | (length & 0x3F));
                        }
                         
                        tempData.writeShort(fontID);
                        tempData.writeBytes(data, data.position, length - 2);
                        break;
                    case 87: // DefineBinaryData
                        tempData = new ByteArray();
                        tempData.endian = Endian.LITTLE_ENDIAN;
                        data.readUnsignedShort(); // tag
                        data.readUnsignedInt(); // reserved
                        tempData.writeBytes(data, data.position, length - 6);
                        tempData.position = 0;
                         
                        try {
                            tempData = new SWFByteArray(tempData);
                            this._embeddedID += 1;
                            this.processSWF(tempData, fontData, startFontID + 2000 * this._embeddedID);
                        } catch (error:ArgumentError) {
                            // Not SWF. Do nothing.
                        }
                         
                        break;
                }
                 
                data.position = pos + length;
            }
        }
         
        /**
         * @private
         */
        private function handler_delayedComplete(event:Event):void {
            this._libLoader.removeEventListener(Event.ENTER_FRAME, this.handler_delayedComplete);
            this._libLoader = null;
            this.close();
            super.dispatchEvent(new Event(Event.COMPLETE));
        }
         
        /**
         * @private
         */
        private function handler_delayedVerifyError(event:Event):void {
            this._libLoader.removeEventListener(Event.ENTER_FRAME, this.handler_delayedVerifyError);
            this._libLoader = null;
            this.close();
            super.dispatchEvent(new IOErrorEvent(IOErrorEvent.VERIFY_ERROR));
        }
         
        /**
         * @private
         */
        private function handler_complete(event:Event):void {
            this.analyze(this._loader.data as ByteArray);
        }
         
        /**
         * @private
         */
        private function handler_libComplete(event:Event):void {
            var id:String;
            var i:uint;
            var fontClass:Class;
            var font:Font;
            var domain:ApplicationDomain = this._libLoader.contentLoaderInfo.applicationDomain;
             
            for (i = 0;i < this._fontCount;i++) {
                id = i.toString();
                while (id.length < 3) id = '0' + id;
                id = FontLoader.CLASS_NAME_PREFIX + id;
                 
                if (domain.hasDefinition(id)) {
                    fontClass = domain.getDefinition(id) as Class;
                    font = new fontClass() as Font;
                     
                    if (font && font.fontName) { // Skip static fonts
                        this._fonts.push(font);
                        if (this._autoRegister) Font.registerFont(fontClass);
                    }
                }
            }
             
            this.close();
            super.dispatchEvent(new Event(Event.COMPLETE));
        }
    }
}
 
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.geom.Rectangle;
 
internal class SWFByteArray extends ByteArray {
     
    /**
     * @private
     */
    private static const TAG_SWF:String = 'FWS';
     
    /**
     * @private
     */
    private static const TAG_SWF_COMPRESSED:String = 'CWS';
     
    public function SWFByteArray(data:ByteArray=null):void {
        super();
        super.endian = Endian.LITTLE_ENDIAN;
        var endian:String;
        var tag:String;
        var position:uint;
         
        if (data) {
            endian = data.endian;
            position = data.position;
            data.endian = Endian.LITTLE_ENDIAN;
            data.position = 0;
             
            if (data.bytesAvailable > 26) {
                tag = data.readUTFBytes(3);
                 
                if (tag == SWFByteArray.TAG_SWF || tag == SWFByteArray.TAG_SWF_COMPRESSED) {
                    this._version = data.readUnsignedByte();
                    data.readUnsignedInt();
                    data.readBytes(this);
                    if (tag == SWFByteArray.TAG_SWF_COMPRESSED) super.uncompress();
                } else throw new ArgumentError('Error #2124: Loaded file is an unknown type.');
                 
                this.readHeader();
            } else {
                throw new ArgumentError('Insufficient data.');
            }
             
            data.endian = endian;
            data.position = position;
        }
    }
     
    /**
     * @private
     */
    private var _bitIndex:uint;
     
    /**
     * @private
     */
    private var _version:uint;
     
    public function get version():uint {
        return this._version;
    }
     
    /**
     * @private
     */
    private var _frameRate:Number;
     
    public function get frameRate():Number {
        return this._frameRate;   
    }
     
    /**
     * @private
     */
    private var _rect:Rectangle;
     
    public function get rect():Rectangle {
        return this._rect;
    }
     
    public function writeBytesFromString(bytesHexString:String):void {
        var length:uint = bytesHexString.length;
         
        for (var i:uint = 0;i<length;i += 2) {
            var hexByte:String = bytesHexString.substr(i, 2);
            var byte:uint = parseInt(hexByte, 16);
            writeByte(byte);
        }
    }
     
    public function readRect():Rectangle {
        var pos:uint = super.position;
        var byte:uint = this[pos];
        var bits:uint = byte >> 3;
        var xMin:Number = this.readBits(bits, 5) / 20;
        var xMax:Number = this.readBits(bits) / 20;
        var yMin:Number = this.readBits(bits) / 20;
        var yMax:Number = this.readBits(bits) / 20;
        super.position = pos + Math.ceil(((bits * 4) - 3) / 8) + 1;
        return new Rectangle(xMin, yMin, xMax - xMin, yMax - yMin);
    }
     
    public function readBits(length:uint, start:int = -1):Number {
        if (start < 0) start = this._bitIndex;
        this._bitIndex = start;
        var byte:uint = this[super.position];
        var out:Number = 0;
        var shift:Number = 0;
        var currentByteBitsLeft:uint = 8 - start;
        var bitsLeft:Number = length - currentByteBitsLeft;
         
        if (bitsLeft > 0) {
            super.position++;
            out = this.readBits(bitsLeft, 0) | ((byte & ((1 << currentByteBitsLeft) - 1)) << (bitsLeft));
        } else {
            out = (byte >> (8 - length - start)) & ((1 << length) - 1);
            this._bitIndex = (start + length) % 8;
            if (start + length > 7) super.position++;
        }
         
        return out;
    }
     
    public function traceArray(array:ByteArray):String { // for debug
        var out:String = '';
        var pos:uint = array.position;
        var i:uint = 0;
        array.position = 0;
         
        while (array.bytesAvailable) {
            var str:String = array.readUnsignedByte().toString(16).toUpperCase();
            str = str.length < 2 ? '0'+str : str;
            out += str+' ';
        }
         
        array.position = pos;
        return out;
    }
     
    /**
     * @private
     */
    private function readFrameRate():void {
        if (this._version < 8) {
            this._frameRate = super.readUnsignedShort();
        } else {
            var fixed:Number = super.readUnsignedByte() / 0xFF;
            this._frameRate = super.readUnsignedByte() + fixed;
        }
    }
     
    /**
     * @private
     */
    private function readHeader():void {
        this._rect = this.readRect();
        this.readFrameRate();       
        super.readShort(); // num of frames
    }
}
posted @ 2013-05-23 17:48  知明所以  阅读(2155)  评论(0编辑  收藏  举报