/
GlyphCache.as
101 lines (84 loc) · 3.1 KB
/
GlyphCache.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
package com.pblabs.engine.debug
{
import flash.display.BitmapData;
import flash.geom.Point;
import flash.text.TextField;
import flash.text.TextFormat;
/**
* Helper class to cache glyphs as bitmaps and draw them fast, with color.
* @author beng
*
*/
public class GlyphCache
{
function GlyphCache()
{
// Set up the text field.
_textField.setTextFormat(_textFormat);
_textField.defaultTextFormat = _textFormat;
}
public function drawLineToBitmap(line:String, x:int, y:int, color:uint, renderTarget:BitmapData):int
{
// Get the color bitmap.
if(!_colorCache[color])
_colorCache[color] = new BitmapData(128, 128, false, color);
const colorBitmap:BitmapData = _colorCache[color] as BitmapData;
// Keep track of current pos.
var curPos:Point = new Point(x, y);
var linesConsumed:int = 1;
// Get each character.
const glyphCount:int = line.length;
for(var i:int=0; i<glyphCount; i++)
{
const char:int = line.charCodeAt(i);
// Special cases...
if(char == 10)
{
// New line!
curPos.x = x;
curPos.y += 16;
linesConsumed++;
continue;
}
// Draw the glyph.
const glyph:Glyph = getGlyph(char);
renderTarget.copyPixels(colorBitmap, glyph.rect, curPos, glyph.bitmap, null, true);
// Update position.
curPos.x += glyph.rect.width - 1;
}
return linesConsumed;
}
protected function getGlyph(charCode:int):Glyph
{
if(_glyphCache[charCode] == null)
{
// Generate glyph.
var newGlyph:Glyph = new Glyph();
_textField.text = String.fromCharCode(charCode);
newGlyph.bitmap = new BitmapData(_textField.textWidth + 1, 16, true, 0x0);
newGlyph.bitmap.draw(_textField);
newGlyph.rect = newGlyph.bitmap.rect;
// Store it in cache.
_glyphCache[charCode ] = newGlyph;
}
return _glyphCache[charCode] as Glyph;
}
public function getLineHeight():int
{
// Do some tall characters.
_textField.text = "HPI";
return _textField.getLineMetrics(0).height;
}
protected const _textFormat:TextFormat = new TextFormat("_typewriter", 11, 0xDDDDDD);
protected const _textField:TextField = new TextField();
protected const _glyphCache:Array = [];
protected const _colorCache:Array = [];
}
}
import flash.display.BitmapData;
import flash.geom.Rectangle;
class Glyph
{
public var rect:Rectangle;
public var bitmap:BitmapData;
}