]>
git.proxmox.com Git - sencha-touch.git/blob - src/src/draw/TextMeasurer.js
2 * Utility class to provide a way to *approximately* measure the dimension of texts without a drawing context.
4 Ext
.define("Ext.draw.TextMeasurer", {
7 uses
: ['Ext.draw.engine.Canvas'],
13 * @private Measure the size of a text with specific font by using DOM to measure it.
14 * Could be very expensive therefore should be used lazily.
15 * @param {String} text
16 * @param {String} font
17 * @return {Object} An object with `width` and `height` properties.
18 * @return {Number} return.width
19 * @return {Number} return.height
21 actualMeasureText: function (text
, font
) {
22 var me
= Ext
.draw
.TextMeasurer
,
23 measureDiv
= me
.measureDiv
,
28 var parent
= Ext
.Element
.create({
31 "position": "relative",
32 "float": "left", // DO NOT REMOVE THE QUOTE OR IT WILL BREAK COMPRESSOR
37 me
.measureDiv
= measureDiv
= Ext
.Element
.create({});
39 "position": 'absolute',
43 "white-space": "nowrap",
48 Ext
.getBody().appendChild(parent
);
49 parent
.appendChild(measureDiv
);
57 measureDiv
.setText('(' + text
+ ')');
58 size
= measureDiv
.getSize();
59 measureDiv
.setText('()');
60 size
.width
-= measureDiv
.getSize().width
;
65 * Measure a single-line text with specific font.
66 * This will split the text to characters and add up their size.
67 * That may *not* be the exact size of the text as it is displayed.
68 * @param {String} text
69 * @param {String} font
70 * @return {Object} An object with `width` and `height` properties.
71 * @return {Number} return.width
72 * @return {Number} return.height
74 measureTextSingleLine: function (text
, font
) {
75 text
= text
.toString();
76 var cache
= this.measureCache
,
77 chars
= text
.split(''),
80 cachedItem
, charactor
, i
, ln
, size
;
91 for (i
= 0, ln
= chars
.length
; i
< ln
; i
++) {
93 if (!(cachedItem
= cache
[charactor
])) {
94 size
= this.actualMeasureText(charactor
, font
);
95 cachedItem
= cache
[charactor
] = size
;
97 width
+= cachedItem
.width
;
98 height
= Math
.max(height
, cachedItem
.height
);
100 return cache
[text
] = {
107 * Measure a text with specific font.
108 * This will split the text to lines and add up their size.
109 * That may *not* be the exact size of the text as it is displayed.
110 * @param {String} text
111 * @param {String} font
112 * @return {Object} An object with `width`, `height` and `sizes` properties.
113 * @return {Number} return.width
114 * @return {Number} return.height
115 * @return {Array} return.sizes Results of individual line measurements, in case of multiline text.
117 measureText: function (text
, font
) {
118 var lines
= text
.split('\n'),
126 return this.measureTextSingleLine(text
, font
);
130 for (i
= 0; i
< ln
; i
++) {
131 line
= this.measureTextSingleLine(lines
[i
], font
);
133 height
+= line
.height
;
134 width
= Math
.max(width
, line
.width
);