41 lines
1.8 KiB
Luau
41 lines
1.8 KiB
Luau
-- examples/vector.luau: parse an SVG, rasterize it, build a Vector and write it as SVG (docs/guide/vector.md).
|
|
local F = require("@rosetta")
|
|
|
|
local svg = [[<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24">
|
|
<rect x="1" y="1" width="22" height="22" rx="4" fill="#2d6cdf"/>
|
|
<path d="M6 12 L10 16 L18 8" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round"
|
|
stroke-linejoin="round"/>
|
|
</svg>]]
|
|
|
|
local icon = assert(F.vector.load(svg))
|
|
print(string.format("%dx%d, viewBox %s, %d paths", icon.width, icon.height, table.concat(icon.viewBox, " "), #icon.paths))
|
|
for i, p in icon.paths do
|
|
print(i, p.fill and p.fill.type or "no fill", p.stroke and "stroke " .. p.strokeWidth or "no stroke", #p.d .. " commands")
|
|
end
|
|
|
|
-- rasterize: the default size, and a larger one (the viewBox scales to fit)
|
|
local small = assert(F.ops.vector.rasterize(icon))
|
|
local big = assert(F.ops.vector.rasterize(icon, 256, 256))
|
|
assert(small.width == 48 and big.width == 256)
|
|
local r, _, b, a = F.ops.image.getPixel(big, 128, 20)
|
|
assert(a == 255 and b > r, "the blue background")
|
|
local png = assert(F.save(big, nil, { format = "png" }))
|
|
print("rasterized to a 256x256 PNG of " .. buffer.len(png) .. " bytes")
|
|
|
|
-- a Vector from scratch: a red triangle, written as SVG and read back
|
|
local v = F.Types.Vector.new(32, 32)
|
|
table.insert(v.paths, {
|
|
d = { { op = "M", 4, 28 }, { op = "L", 16, 4 }, { op = "L", 28, 28 }, { op = "Z" } },
|
|
fill = { type = "color", color = { 220, 40, 40, 255 } },
|
|
fillRule = "nonzero",
|
|
strokeWidth = 0,
|
|
opacity = 1,
|
|
})
|
|
local text = assert(F.saveString(v, { format = "svg" }))
|
|
local again = assert(F.vector.load(text))
|
|
assert(#again.paths == 1)
|
|
local tri = assert(F.ops.vector.rasterize(again))
|
|
local tr = F.ops.image.getPixel(tri, 16, 20)
|
|
assert(tr == 220)
|
|
print("triangle SVG: " .. #text .. " characters")
|