From 7564e3bbe50a4567e804a60215dc12c8db4ccb46 Mon Sep 17 00:00:00 2001 From: James Harton Date: Thu, 5 Jan 2017 10:29:14 +1300 Subject: [PATCH] Implement String.Chars for Shapes. W00T. --- lib/string/chars/vivid/shape.ex | 25 +++++++++++++++++++++++++ lib/vivid/rasterize/line.ex | 8 +++++++- 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 lib/string/chars/vivid/shape.ex diff --git a/lib/string/chars/vivid/shape.ex b/lib/string/chars/vivid/shape.ex new file mode 100644 index 0000000..a51dc54 --- /dev/null +++ b/lib/string/chars/vivid/shape.ex @@ -0,0 +1,25 @@ +defmodule Vivid.ShapeToString do + alias Vivid.{Bounds, Frame, Transform, RGBA} + + def to_string(shape) do + bounds = Bounds.bounds(shape) + width = Bounds.width(bounds) + 3 |> round + height = Bounds.height(bounds) + 3 |> round + frame = Frame.init(width, height, RGBA.white) + + shape = shape + |> Transform.center(frame) + |> Transform.apply + + frame + |> Frame.push(shape, RGBA.black) + |> Kernel.to_string + end +end + +Enum.each(~w(Arc Box Circle Group Line Path Polygon), fn mod -> + mod = Module.concat(Vivid, mod) + defimpl String.Chars, for: mod do + def to_string(shape), do: Vivid.ShapeToString.to_string(shape) + end +end) diff --git a/lib/vivid/rasterize/line.ex b/lib/vivid/rasterize/line.ex index 5d17ab7..afc0357 100644 --- a/lib/vivid/rasterize/line.ex +++ b/lib/vivid/rasterize/line.ex @@ -57,7 +57,9 @@ defimpl Vivid.Rasterize, for: Vivid.Line do reduce_points(points, steps, current_x, current_y, x_increment, y_increment) end + |> pixel_round |> clip(bounds) + |> Enum.into(MapSet.new) end defp reduce_points(points, 0, _, _, _, _), do: points @@ -73,10 +75,14 @@ defimpl Vivid.Rasterize, for: Vivid.Line do defp choose_largest_of(a, b) when a > b, do: a defp choose_largest_of(_, b), do: b + defp pixel_round(points) do + points + |> Stream.map(&Point.round(&1)) + end + defp clip(points, %Bounds{}=bounds) do points |> Stream.filter(&Bounds.contains?(bounds,&1)) - |> Enum.into(MapSet.new) end end \ No newline at end of file