Skip to content

Instantly share code, notes, and snippets.

@jmatsu
Created September 3, 2023 04:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmatsu/363f9ca8bfcc01577c939d86676e0484 to your computer and use it in GitHub Desktop.
Save jmatsu/363f9ca8bfcc01577c939d86676e0484 to your computer and use it in GitHub Desktop.
Just a snippet to parse vector drawable's pathData for VectorImage in Compose
# ruby parse_vector_pathData.rb "<pathData>"
#
# @example ruby parse_vector_pathData.rb "M2...Z"
#
# <pathData> is a pathData attribute of path node.
pathData = ARGV[0]
kotlinPathNodeChunks = []
cursor_idx = 0
while cursor_idx != nil && cursor_idx < pathData.length do
current_cursor_idx = cursor_idx
# Node Kind
c = pathData[current_cursor_idx]
# Node Data
data_length = pathData[current_cursor_idx + 1..].index(/[A-Za-z]/) || pathData[current_cursor_idx + 1..].length
data = pathData[current_cursor_idx + 1, data_length]
# Move to the next Node Kind
cursor_idx = current_cursor_idx + data_length + 1
STDERR.puts "current_cursor_idx: #{current_cursor_idx}, cursor_idx: #{cursor_idx}"
STDERR.puts "c: #{c}, next_c: #{pathData[cursor_idx]}"
STDERR.puts data
args = data.split(/[ ,]/)
case c
when "M"
kotlinPathNodeChunks << "PathNode.MoveTo(x = #{args[0]}f, y = #{args[1]}f)"
when "L"
kotlinPathNodeChunks << "PathNode.LineTo(x = #{args[0]}f, y = #{args[1]}f)"
when "C"
kotlinPathNodeChunks << <<-EOF
PathNode.CurveTo(
x1 = #{args[0]}f,
y1 = #{args[1]}f,
x2 = #{args[2]}f,
y2 = #{args[3]}f,
x3 = #{args[4]}f,
y3 = #{args[5]}f
)
EOF
when "H"
kotlinPathNodeChunks << "PathNode.HorizontalTo(x = #{args[0]}f)"
when "h"
kotlinPathNodeChunks << "PathNode.RelativeHorizontalTo(dx = #{args[0]}f)"
when "V"
kotlinPathNodeChunks << "PathNode.VerticalTo(y = #{args[0]}f)"
when "v"
kotlinPathNodeChunks << "PathNode.RelativeVerticalTo(dy = #{args[0]}f)"
when "S"
kotlinPathNodeChunks << <<-EOF
PathNode.ReflectiveCurveTo(
x1 = #{args[0]}f,
y1 = #{args[1]}f,
x2 = #{args[2]}f,
y2 = #{args[3]}f
)
EOF
when "s"
kotlinPathNodeChunks << <<-EOF
PathNode.RelativeReflectiveCurveTo(
dx1 = #{args[0]}f,
dy1 = #{args[1]}f,
dx2 = #{args[2]}f,
dy2 = #{args[3]}f
)
EOF
when "A"
kotlinPathNodeChunks << <<-EOF
PathNode.ArcTo(
horizontalEllipseRadius = #{args[0]}f,
verticalEllipseRadius = #{args[1]}f,
theta = #{args[2]}f,
isMoreThanHalf = #{args[3] == "1" ? "true" : "false"},
isPositiveArc = #{args[4] == "1" ? "true" : "false"},
arcStartX = #{args[5]}f,
arcStartY = #{args[6]}f
)
EOF
when "Z"
when "z"
kotlinPathNodeChunks << "PathNode.Close"
else
raise "unknown command: #{c}" # more nodes are not supported yet...
end
end
puts kotlinPathNodeChunks.join(",\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment