本指南详细介绍了如何在 Python 中旋转 SVG。它包含环境配置详细信息和步骤列表,以及在 Python 中旋转 SVG 的可运行代码片段。它介绍了从头开始创建 SVG 图像并将其旋转到任何所需角度的过程,以全面展示该功能。
使用 Python 旋转 SVG 的步骤
- 通过安装 Aspose.SVG 配置 IDE 来旋转矢量图像
- 将示例字符串指定为包含一行的 SVG 文件
- 声明 SVGDocument 类的实例
- 访问SVGDocument类对象的根元素
- 传递 SVG 图像的旋转角度时指定变换属性
- 使用 save 方法导出旋转后的 SVG
上述步骤概述了如何在 Python 中旋转 SVG 图像。通过启动包含一行的 SVG 文件来开始矢量图像旋转过程。但是,如果您想旋转任何特定的 SVG 图像,算法保持不变。首先,将中间 SVG 图像导出到磁盘,应用旋转变换,然后将旋转后的矢量图像保存到磁盘。
使用 Python 旋转 SVG 图像的代码
import aspose.svg | |
import os | |
from aspose.svg import * | |
path = "C://" | |
# Specify SVG content | |
documentContent = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"400\" height=\"400\">"" <line x1=\"50\" y1=\"50\" x2=\"350\" y2=\"350\" stroke=\"black\" stroke-width=\"2\" /></svg>" | |
# Instantiate an SVGDocument object | |
document = SVGDocument(documentContent, ".") | |
# Get root svg element of the document | |
svg_element = document.root_element | |
# Access the line segment | |
lineElement = svg_element.query_selector("line") | |
# Save the SVG document to a file | |
output_path = os.path.join(path, "BeforeRotation.svg") | |
document.save(output_path) | |
# Set a transform attribute value | |
lineElement.set_attribute("transform", "rotate(-90 200 265)") | |
# Save the SVG file | |
document.save("AfterRotation.svg") |
此示例代码展示了如何顺利地执行 Python 中的 SVG 旋转任务。但值得注意的是,该过程利用 query_selector() 方法来选择要旋转的目标元素。此外,在传递旋转角度和要围绕其执行旋转的坐标时调用 rotate() 方法。您可以将自定义值作为参数传递以改进 SVG 旋转过程。
本指南帮助我们了解了在 Python 中旋转 SVG 图像的细节。然而,如果您热衷于了解将任何文本渲染为 SVG 图像的过程,请阅读 使用 Python 将文本转换为 SVG 上的文章。