Download raw (3.5 KB)
class Font (object): def __init__ (self, path = False, resolution = False, scale = False): self.path = '' self.cache = True self.source = {} self.chars = {} self.resolution = 10 if resolution == False else resolution self.length = 0 self.name = '' self.cacheDir = 'shape_font_cache' #'~/tmp/shape_font_cache' self.cacheFilePath = '{0}/{1}-{2}.json' # Basepath, name, resolution if path <> False: self.load (path) if resolution <> False: self.render (resolution = resolution) if scale <> False: self.scale (scale) def load (self, path = False): if path <> False: self.path = path try: with open(self.path, 'r') as font_file: self.source = json.load (font_file) font_file.close() self.name = self.source["name"] print self.name, self.source["name"] for char in self.source["chars"]: char = Character (char) self.addChar (char) except: return False return True def write (self, path = False): self.scale (1) writer = FontWriter (self) return writer.write (path) def get (self, key): if key in self.chars: return deepcopy (self.chars[key]) else: return False def addChar (self, char): self.chars[char.key] = char def getChar (self, char): return self.get (ord (char)) def render (self, resolution = False): if resolution <> False: self.resolution = resolution if self.cache == True: if self.loadCache () == True: return True for key in self.chars: self.chars[key].render(self.resolution) if self.cache == True: self.writeCache () def scale (self, scale = 1): self.height = self.chars[self.chars.keys()[0]]._height * scale * 1.60 for key in self.chars: self.chars[key].scale = scale @property def cacheFile (self): return self.cacheFilePath.format (self.cacheDir, self.name, self.resolution) def loadCache (self): if self.cacheExists(): cache = json.load (open (self.cacheFile, 'r')) self.putCacheObject (cache) return True else: return False def writeCache (self): if self.cacheDirExists () == False: self.createCacheDir () handle = open (self.cacheFile, 'w') return json.dump (self.getCacheObject (), handle) def cacheExists (self): if os.path.exists (self.cacheFile): return True else: if self.cacheDirExists () == False: self.createCacheDir () return False def cacheDirExists (self): return os.path.exists (self.cacheDir) def createCacheDir (self): os.makedirs (self.cacheDir) def getCacheObject (self): return {char: self.chars[char].shape for char in self.chars} def putCacheObject (self, cache): for char in cache: self.chars[int (char)].shape = cache[char]