valueAndUnit.ts 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /// <reference path="../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON.GUI {
  3. export class ValueAndUnit {
  4. private _value = 1;
  5. public ignoreAdaptiveScaling = false;
  6. public constructor(value, public unit = ValueAndUnit.UNITMODE_PIXEL, public negativeValueAllowed = true) {
  7. this._value = value;
  8. }
  9. public get isPercentage(): boolean {
  10. return this.unit === ValueAndUnit.UNITMODE_PERCENTAGE;
  11. }
  12. public get isPixel(): boolean {
  13. return this.unit === ValueAndUnit.UNITMODE_PIXEL;
  14. }
  15. public get internalValue(): number {
  16. return this._value;
  17. }
  18. public getValue(host: AdvancedDynamicTexture): number {
  19. if (host && !this.ignoreAdaptiveScaling && this.unit !== ValueAndUnit.UNITMODE_PERCENTAGE) {
  20. if (host.idealWidth) { // horizontal
  21. return (this._value * host.getSize().width) / host.idealWidth;
  22. }
  23. if (host.idealHeight) { // vertical
  24. return (this._value * host.getSize().height) / host.idealHeight;
  25. }
  26. }
  27. return this._value;
  28. }
  29. public toString(host: AdvancedDynamicTexture): string {
  30. switch (this.unit) {
  31. case ValueAndUnit.UNITMODE_PERCENTAGE:
  32. return (this.getValue(host) * 100) + "%";
  33. case ValueAndUnit.UNITMODE_PIXEL:
  34. return this.getValue(host) + "px";
  35. }
  36. return this.unit.toString();
  37. }
  38. public fromString(source: string | number ): boolean {
  39. var match = ValueAndUnit._Regex.exec(source.toString());
  40. if (!match || match.length === 0) {
  41. return false;
  42. }
  43. var sourceValue = parseFloat(match[1]);
  44. var sourceUnit = this.unit;
  45. if (!this.negativeValueAllowed) {
  46. if (sourceValue < 0) {
  47. sourceValue = 0;
  48. }
  49. }
  50. if (match.length === 4) {
  51. switch(match[3]) {
  52. case "px":
  53. sourceUnit = ValueAndUnit.UNITMODE_PIXEL;
  54. break;
  55. case "%":
  56. sourceUnit = ValueAndUnit.UNITMODE_PERCENTAGE;
  57. sourceValue /= 100.0;
  58. break;
  59. }
  60. }
  61. if (sourceValue === this._value && sourceUnit === this.unit) {
  62. return false;
  63. }
  64. this._value = sourceValue;
  65. this.unit = sourceUnit;
  66. return true;
  67. }
  68. // Static
  69. private static _Regex = /(^-?\d*(\.\d+)?)(%|px)?/;
  70. private static _UNITMODE_PERCENTAGE = 0;
  71. private static _UNITMODE_PIXEL = 1;
  72. public static get UNITMODE_PERCENTAGE(): number {
  73. return ValueAndUnit._UNITMODE_PERCENTAGE;
  74. }
  75. public static get UNITMODE_PIXEL(): number {
  76. return ValueAndUnit._UNITMODE_PIXEL;
  77. }
  78. }
  79. }