python-3.x - Python - 将 2 个 SVG 元素合并为一个 SVG 元素
问题描述
我正在加载两个应该具有的 SVG:
- 从左下角的起点 (x %, y %)
- 总宽度和高度百分比。
我想将它们合并到一个 SVG 中,其中第一个 SVG 和第二个 SVG 位于请求的位置。
我试着用svglib
class Position:
def __init__(self, x_start_position: float, y_start_position: float, height: float, width: float):
self.x_start_position = x_start_position
self.y_start_position = y_start_position
self.height = height
self.width = width
drawing_1_position = Position(0, 0, 100, 100)
drawing_2_position = Position(20, 20, 80, 80)
# the first drawing should be taken with it's full size and start from the bottom left corner
# the second drawing should be taken with 80% of it's height and 80% of it's width starting 20% from the bottom left corner for it's height and length
drawing_1 = svglib.svg2rlg(io.StringIO(svg_1))
drawing_2 = svglib.svg2rlg(io.StringIO(svg_2))
???
谢谢
解决方案
解决方案是创建一个包装图:
import io
import svglib
from reportlab.graphics.shapes import Drawing
from reportlab.graphics.renderSVG import SVGCanvas, draw
with open("sample1.svg") as fp:
svg_1_content = fp.read()
with open("sample2.svg") as fp:
svg_2_content = fp.read()
svg_1_element = svglib.svg2rlg(io.StringIO(svg_1_content))
svg_2_element = svglib.svg2rlg(io.StringIO(svg_2_content))
width = 100
height = 100
svg_element = svglib.svg2rlg(io.StringIO(background_content))
d = Drawing(width, height) # setting the width and height
svg_1_element.scale(width / svg_1_element.width, height / svg_2_element.height)
svg_2_element.scale(width / svg_1_element.width, height / svg_2_element.height)
d.add(svg_1_element)
d.add(svg_2_element)
svg 1 和 2 应该缩放到想要的大小 - 这只是一个简单的例子
在 2 个对象位于绘图内之后 - 要从中创建 svg,您可以使用以下代码:
s = getStringIO()
c = SVGCanvas((d.width, d.height))
draw(d, c, 0, 0)
c.save(s)
print(s.getvalue()) # here is the svg output (that can be shown inside a html web page)
推荐阅读
- c# - C#:如何拆分具有变化前缀的字符串
- ruby - 确定字符串的结尾是否与单独字符串的开头重叠
- css - CSS - 为什么隐藏 flexbox 的开头?以及如何解决保持项目居中的问题?
- facebook - 如何使用图形 API 获取 Facebook 相册的图像
- corda - Corda NodeDriver MissingContractAttachments for Cash 即使有要扫描的包集
- python - 如何更改 self.button 的状态
- ruby-on-rails - 在 Rails 中将创建模型和关联逻辑放在哪里?
- factory-boy - 从 Faker("name") 中排除前缀和后缀
- python - 创建对象列表python
- c# - aspnet 核心 web.config 未加载