1-- Copyright (C) 2012 Jared Krinke. 2-- 3-- This is free software; you can redistribute it and/or 4-- modify it under the terms of the GNU General Public License 5-- as published by the Free Software Foundation; either version 2 6-- of the License, or (at your option) any later version. 7-- 8-- This program is distributed in the hope that it will be useful, 9-- but WITHOUT ANY WARRANTY; without even the implied warranty of 10-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11-- GNU General Public License for more details. 12-- 13-- You should have received a copy of the GNU General Public License 14-- along with this program; if not, write to the Free Software 15-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 16 17Label = { } 18 19local setXByAlignment = { 20 left = function(self, x, y) self.x = x end, 21 center = function(self, x, y) self.x = x + self:getSize() / 2 end, 22 right = function(self, x, y) self.x = x + self:getSize() end, 23} 24 25function Label.new(text, alignment, stretch) 26 local label = Entity.new() 27 28 label.stretch = stretch 29 label.totalWidth = 0 30 31 if not isString(text) then 32 text = "" 33 end 34 35 label.textElement = label.elements:add(Element.Text.new(text)) 36 37 if isString(alignment) then 38 label.alignment = alignment 39 label.textElement.alignment = alignment 40 end 41 42 function label.setText(self, text) 43 label.textElement.text = text 44 end 45 46 function label.setColor(self, color) 47 label.textElement.color = color 48 end 49 50 function label.setLayer(self, layer) 51 layer:addChild(self) 52 end 53 54 function label.getPosition(self) 55 return self.x, self.y + self.height 56 end 57 58 function label.setPosition(self, x, y) 59 local setXInternal = setXByAlignment[self.alignment] 60 61 if not isFunction(setXInternal) then 62 setXInternal = setXByAlignment.left 63 end 64 65 setXInternal(self, x, y) 66 self.y = y - self.height 67 end 68 69 function label.setTextSize(self, width, height) 70 self.width = width 71 self.height = height 72 end 73 74 function label.getActive(self) 75 return false 76 end 77 78 function label.getMinimumSize(self) 79 return #self.textElement.text * self.width, self.height 80 end 81 82 function label.getDesiredSize(self) 83 return self:getMinimumSize() 84 end 85 86 function label.getSize(self) 87 local minimumWidth, minimumHeight = self:getMinimumSize() 88 return self.totalWidth, minimumHeight 89 end 90 91 function label.setSize(self, width, height) 92 -- Only change size if label should stretch text 93 if isBoolean(self.stretch) and self.stretch then 94 self.width = width / #self.textElement.text 95 self.height = height 96 else 97 if isString(self.alignment) and self.alignment == "right" then 98 -- Add padding 99 local extraPadding = width - self.totalWidth 100 101 if isNumber(self.x) then 102 self.x = self.x + extraPadding 103 end 104 end 105 106 self.totalWidth = width 107 end 108 end 109 110 return label 111end 112 113