2016-06-09 22:49:38 +01:00
|
|
|
"""Calculate the area of a glyph."""
|
|
|
|
|
2016-06-09 23:03:50 +01:00
|
|
|
from __future__ import print_function, division, absolute_import
|
|
|
|
from fontTools.misc.py23 import *
|
2016-06-09 22:49:38 +01:00
|
|
|
from fontTools.pens.basePen import BasePen
|
|
|
|
|
|
|
|
|
|
|
|
def polygon_area(p0, p1):
|
2016-06-12 03:12:02 +01:00
|
|
|
return -(p1[0] - p0[0]) * (p1[1] + p0[1]) * 0.5
|
2016-06-09 22:49:38 +01:00
|
|
|
|
|
|
|
|
|
|
|
def quadratic_curve_area(p0, p1, p2):
|
2016-06-12 03:14:09 +01:00
|
|
|
x0, y0 = p0[0], p0[1]
|
|
|
|
x1, y1 = p1[0] - x0, p1[1] - y0
|
|
|
|
x2, y2 = p2[0] - x0, p2[1] - y0
|
|
|
|
return (x1*y2 - x2*y1) / 3
|
2016-06-09 22:49:38 +01:00
|
|
|
|
|
|
|
|
|
|
|
def cubic_curve_area(p0, p1, p2, p3):
|
2016-06-09 23:28:06 +01:00
|
|
|
x0, y0 = p0[0], p0[1]
|
|
|
|
x1, y1 = p1[0] - x0, p1[1] - y0
|
|
|
|
x2, y2 = p2[0] - x0, p2[1] - y0
|
|
|
|
x3, y3 = p3[0] - x0, p3[1] - y0
|
2016-06-12 03:12:02 +01:00
|
|
|
return -(
|
2016-06-09 23:28:06 +01:00
|
|
|
x1 * ( - y2 - y3) +
|
|
|
|
x2 * (y1 - 2*y3) +
|
|
|
|
x3 * (y1 + 2*y2 )
|
|
|
|
) * 0.15
|
2016-06-09 22:49:38 +01:00
|
|
|
|
|
|
|
|
|
|
|
class AreaPen(BasePen):
|
|
|
|
|
2016-06-12 03:13:32 +01:00
|
|
|
def __init__(self, glyphset=None):
|
2016-06-09 23:28:06 +01:00
|
|
|
BasePen.__init__(self, glyphset)
|
|
|
|
self.value = 0
|
2016-06-09 22:49:38 +01:00
|
|
|
|
2016-06-09 23:28:06 +01:00
|
|
|
def _moveTo(self, p0):
|
2016-06-12 03:13:32 +01:00
|
|
|
self.__startPoint = p0
|
2016-06-09 22:49:38 +01:00
|
|
|
|
2016-06-09 23:28:06 +01:00
|
|
|
def _lineTo(self, p1):
|
|
|
|
p0 = self._getCurrentPoint()
|
|
|
|
self.value += polygon_area(p0, p1)
|
2016-06-09 22:49:38 +01:00
|
|
|
|
2016-06-09 23:28:06 +01:00
|
|
|
def _curveToOne(self, p1, p2, p3):
|
|
|
|
p0 = self._getCurrentPoint()
|
|
|
|
self.value += cubic_curve_area(p0, p1, p2, p3)
|
|
|
|
self.value += polygon_area(p0, p3)
|
2016-06-09 23:12:11 +01:00
|
|
|
|
2016-06-09 23:33:36 +01:00
|
|
|
def _qCurveToOne(self, p1, p2):
|
2016-06-09 23:28:06 +01:00
|
|
|
p0 = self._getCurrentPoint()
|
|
|
|
self.value += quadratic_curve_area(p0, p1, p2)
|
|
|
|
self.value += polygon_area(p0, p2)
|
2016-06-12 03:13:32 +01:00
|
|
|
|
|
|
|
def _closePath(self):
|
|
|
|
p0 = self._getCurrentPoint()
|
|
|
|
if p0 != self.__startPoint:
|
2016-06-12 11:35:24 +01:00
|
|
|
self.value += polygon_area(p0, self.__startPoint)
|