无法借助svgelements获取SVG正确包围盒以裁剪空白的问题排查
问题:使用svgelements获取SVG包围盒并裁剪空白失效(复杂SVG场景)
前置说明:目前Stack Overflow上还没有Python库svgelements的标签,因此无法在提问中添加该标签,但解决方案不局限于使用该库。
我需要实现的功能是:加载SVG文件,计算包含所有带变换元素的整体包围盒,然后将SVG的viewBox设置为这个包围盒,以此裁剪掉SVG周围的空白区域。
针对结构简单的SVG,我用以下代码实现时效果正常,但处理一个结构复杂的SVG时完全失效——Chrome开发者工具能获取到正确的包围盒并设置viewBox达到预期效果,但svgelements返回的包围盒数值和正确值不符。
我的代码如下:
from pathlib import Path import svgelements as se def get_bbox(svg_file): svg_file = Path(svg_file) print(svg_file.name) svg = se.SVG.parse(str(svg_file)) bb = svg.bbox() minx, miny, maxx, maxy = bb width = maxx - minx height = maxy - miny # 设置SVG的物理尺寸与viewBox一致 view_box = se.Viewbox(f"{minx} {miny} {width} {height}") svg.values["attributes"]["height"] = str(view_box.height) svg.values["height"] = str(view_box.height) svg.values["attributes"]["width"] = str(view_box.width) svg.values["width"] = str(view_box.width) svg.viewbox = view_box # 添加边框便于查看内容位置 if "style" not in svg.values["attributes"]: svg.values["attributes"]["style"] = "" if "border" not in svg.values["attributes"]["style"]: svg.values["attributes"]["style"] += "border: solid black 1px;" svg.write_xml(str(svg_file.with_stem(svg_file.stem + "-new")))
我遇到问题的SVG是一个结构复杂的任天堂主题SVG文件。
请问是我在代码中忽略了某些处理细节,还是这个SVG本身存在导致svgelements计算错误的问题?
内容的提问来源于stack exchange,提问作者Shmack
相关产品推荐
相关产品推荐

