我如何最容易地首先缩放一个对象,比如当前大小的2倍,然后垂直和水平翻转,或两者兼而有之?
到目前为止,我可以将“scale(2,2)”设置为它的宽度和高度的2倍,但是我不能将其翻转为与垂直翻转的比例(-1,1)相同。
我正在以编程方式创建SVG对象,作为要导出的格式。
要同时应用缩放和翻转,只需在变换中列出两者。
transform="scale(2,2) scale(-1,1)"
或者简单地组合这些值
transform="scale(-2,2)"
当然,您使用负标度的问题是对象在SVG的原点(左上角)翻转,因此它们可以离开文档的边缘。您还需要通过添加翻译来纠正此问题。
因此,例如,假设我们有一个100x100的文档。
<svg width="100" height="100">
<polygon points="100,0,100,100,0,100"/>
</svg>
要垂直翻转,我们可以:
<polygon points="100,0,100,100,0,100" transform="scale(2,-2)"/>
并且为了校正屏幕外的移动,我们要么在翻转之前将其移动为负(因此它会在屏幕上翻转):
<polygon points="100,0,100,100,0,100" transform="scale(2,-2) translate(0,-100)"/>
(此处列出的是翻译,因为变换列表从右到左有效应用)
或者我们可以在之后将其转换为正数(按比例缩放):
<polygon points="100,0,100,100,0,100" transform="translate(0,200) scale(-2,2)"/>
Here is a demo showing vertical flip, horizontal flip and both flips
更新
翻转(就位)屏幕上某处的现有对象。首先确定它的边界框(minX,minY,maxX,maxY)或centreX,centreY,如果你已经知道了。
然后将以下内容添加到其变换中:
translate(<minX+maxX>,0) scale(-1, 1) // for flip X
translate(0,<minY+maxY>) scale(1, -1) // for flip Y
或者如果你有中心,你可以使用
translate(<2 * centreX>,0) scale(-1, 1) // for flip X
所以在你的例子中:
<rect x="75" y="75" width="50" height="50" transform="translate(-100, -100) scale(2, 2) scale(1, 1) rotate(45, 100, 100)" />
minX + maxX达到200.因此,为了横向翻转,我们前置:
translate(200,0) scale(-1, 1)
所以最终的对象变成:
<rect x="75" y="75" width="50" height="50" transform="translate(200,0) scale(-1, 1) translate(-100, -100) scale(2, 2) scale(1, 1) rotate(45, 100, 100)" />
Here是Livescript-ish代码片段,您可以通过任何因素水平翻转和缩放:
# scale is 1 by default
if mirror or scale isnt 1
[minx, miny, width, height] = svg.attributes.viewBox |> split-by ',' |> cast-each-as (Number)
s = scale
# container is the root `g` node
container.attributes.transform = if mirror
"translate(#{s * (width + minx) + minx}, #{-miny * (s-1)}) scale(#{-s},#{s})"
else
"translate(#{-minx * (s-1)}, #{-miny * (s-1)}) scale(#{s},#{s})"
if scale isnt 1
svg.attributes
..viewBox = "#{minx},#{miny},#{width * scale},#{height * scale}"
..width = "#{width * scale}"
..height = "#{height * scale}"