optimize text size measurement code and fix ugly

off by one error
This commit is contained in:
Fabian Jakobs 2010-12-15 14:13:44 +01:00
commit 634e9ac890

View file

@ -39,6 +39,7 @@ define(function(require, exports, module) {
var oop = require("pilot/oop");
var dom = require("pilot/dom");
var lang = require("pilot/lang");
var EventEmitter = require("pilot/event_emitter").EventEmitter;
var Text = function(parentEl) {
@ -79,7 +80,7 @@ var Text = function(parentEl) {
self.$characterSize = size;
self._dispatchEvent("changeCharaterSize", {data: size});
}
}, 1000);
}, 500);
};
this.$fontStyles = {
@ -91,32 +92,37 @@ var Text = function(parentEl) {
},
this.$measureSizes = function() {
var measureNode = document.createElement("div");
var style = measureNode.style;
style.width = style.height = "auto";
style.left = style.top = "-1000px";
style.visibility = "hidden";
style.position = "absolute";
style.overflow = "visible";
if (!this.$measureNode) {
var measureNode = this.$measureNode = document.createElement("div");
var style = measureNode.style;
style.width = style.height = "auto";
style.left = style.top = "-1000px";
style.visibility = "hidden";
style.position = "absolute";
style.overflow = "visible";
style.whiteSpace = "nowrap";
// in FF 3.6 monospace fonts can have a fixed sub pixel width.
// that's why we have to measure many characters
// Note: characterWidth can be a float!
var n = 1000;
measureNode.innerHTML = lang.stringRepeat("Xy", n);
document.body.insertBefore(measureNode, document.body.firstChild);
}
var style = this.$measureNode;
for (var prop in this.$fontStyles) {
var value = dom.computedStyle(this.element, prop);
style[prop] = value;
}
// in FF 3.6 monospace fonts can have a fixed sub pixel width.
// that's why we have to measure many characters
// Note: characterWidth can be a float!
measureNode.innerHTML = new Array(10000).join("Xy");
document.body.insertBefore(measureNode, document.body.firstChild);
var size = {
height: measureNode.offsetHeight,
width: measureNode.offsetWidth / 20000
height: this.$measureNode.offsetHeight,
width: this.$measureNode.offsetWidth / (n * 2)
};
document.body.removeChild(measureNode);
return size;
};