Skip to content

Polyline/path function #81

Description

@mgunyho

Hi! I'm learning Racket during Advent of Code, and I'm really enjoying how easy it is to create quick visualizations of the problems using Pict. However, I have several times needed to draw arbitrary polygons or paths from a list of xy coordinates, and I was surprised that there's no such function in Pict. I think a general-purpose drawing library should have a function like this (ideally, there should be something equivalent to SVG paths, with Bezier curves and such, but that's a bit more advanced).

Here's a quick function I wrote to do this:

(define (polyline coords #:closed? [closed? #t])
  ; coords: list of xy pairs in the form (cons x y)
  (define min-x (apply min (map car coords)))
  (define min-y (apply min (map cdr coords)))
  (define size-x (- (apply max (map car coords)) min-x))
  (define size-y (- (apply max (map cdr coords)) min-y))
  (define coords-shifted (for/list ([xy coords])
                           (cons (- (car xy) min-x) (- (cdr xy) min-y))))
  (dc (λ (dc dx dy)
        (define old-brush (send dc get-brush))
        (send dc set-brush (new brush% [style 'transparent]))

        (define path (new dc-path%))
        (send path move-to (car (first coords-shifted)) (cdr (first coords-shifted)))
        (for-each (λ (xy) (send path line-to (car xy) (cdr xy))) (rest coords-shifted))
        (cond [closed? (send path close)])

        (send dc draw-path path dx dy)
        (send dc set-brush old-brush)
        )
      size-x size-y))

It would of course need arguments to properly specify the line color and fill style etc. I'm also not sure if a list of pairs is the best way to specify the coordinates (pict seems to deal with x and y separately instead of using 2D vectors).

Do you think that something like this should be included in the library?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions