SOLVED How to turn “line” segment into “curve” segment with code?



  • this is part of my tool (for testing the code below I created the test glyph only with rectangle contour in it):

    def interpolation(v1, v2, t):
        return v1 * (1 - t) + v2 * t
    
    def interpolatePoint(p1,p2,t):
        p1x,p1y = p1.position
        p2x,p2y = p2.position
        return  interpolation(p1x, p2x, t), interpolation(p1y, p2y, t)
    
    def turnLineIntoCubicBez(segment, contour):
        if segment.index == 0:
            prevPoint = contour.points[-1]
        else:
            prevPoint = contour.segments[segment.index - 1].points[-1]
        point = segment.points[-1]
        h1x, h1y = interpolatePoint(prevPoint,point,1/3)
        h2x, h2y = interpolatePoint(prevPoint,point,1-1/3)
    
        contour.insertPoint(prevPoint.index,(h1x, h1y),type="offcurve")
        contour.insertPoint(prevPoint.index,(h2x, h2y),type="offcurve")
    
    g = CurrentGlyph()
    c = g.contours[0]
    s = c.segments[0]
    turnLineIntoCubicBez(s, c)
    

    It is basically meant to add offcurve points to the line segment, so the segment turns into the curve.
    Ofcourse, I got an error an and RF crashes, because the segment of "line" type cannot have offcurve points. What is the best way to achieve this (line turning into the curve) in a proper way?

    Best
    R


  • admin

    don't know the context but you can also use the MathGlyphPen from fontMath to convert all line segments to curve segments



  • @gferreira said in How to turn the "line" segment into the "curve" segment with the code?:

    from variableFontGenerator import CompatibleContourPointPen

    glyph = CurrentGlyph()

    for contour in glyph:
    pointTypes = ['curve' for segment in contour]
    pen = CompatibleContourPointPen(pointTypes)
    contour.drawPoints(pen)
    contour.naked().clear()
    pen.drawPoints(contour.naked())

    Thanks Gustavo!!!
    It works like a charm!



  • hello @RafaŁ-Buchner,

    have a look at the Batch extension source code, it has a CompatibleContourPointPen which takes a list of segment types to match.

    this seems to work (you’ll need to have the Batch extension installed):

    from variableFontGenerator import CompatibleContourPointPen
    
    glyph = CurrentGlyph()
    
    for contour in glyph:
        pointTypes = ['curve' for segment in contour]
        pen = CompatibleContourPointPen(pointTypes)
        contour.drawPoints(pen)
        contour.naked().clear()
        pen.drawPoints(contour.naked())
    

    cheers!



  • first thing that I can think of is to use Pen protocol to redraw whole glyph with this particular line turned into the curve, but is it the "best" way?


Log in to reply