【问题标题】:How to specify the portion of the image to be rendered inside SVG:image tag?如何指定要在 SVG:image 标签内渲染的图像部分?
【发布时间】:2013-06-07 11:50:25
【问题描述】:

我有一个带有很多图标的 PNG 文件。我想在我的 SVG 中使用它。我使用 svg:image 标签:

<image xlink:href="icons.png" height="50px" width="50px"></image>

这会渲染整个图像。如何指定要渲染的文件部分? (我需要 CSS 的 background-position 属性的 SVG 等效项)

更新
我怀疑preserveAspectRatio 属性是我需要的,但无法弄清楚如何将它与&lt;image&gt; 一起使用。见this example

【问题讨论】:

标签: image svg icons


【解决方案1】:

您可以使用 preserveAspectRatio 以有限的方式实现此效果。但是您受到 preserveAspectRatio 提供的定位选项的限制。因此,只要您的精灵最多有 3x3 图像或位于角落或侧面,它就可以工作。

我能想到的其他几种方法可以以更灵活的方式实现相同的效果。

  • 使用剪辑或剪辑路径样式属性以及在页面上仔细定位图像
  • 将图像嵌入到另一个&lt;svg&gt; 元素中,并使用viewBox 选择所需的精灵部分。

以下示例演示了上述三种主要技术。

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="8cm" height="8cm" viewBox="0 0 400 400" version="1.1"
     xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <desc>Testing image elements</desc>

  <!-- Outline the drawing area in blue -->
  <rect fill="none" stroke="blue" 
        x="1" y="1" width="398" height="398"/>

  <!-- Use preserveAspectRatio to show the top 64 pixels of the image (Stack Overflow logo) -->
  <image x="100px" y="100px" width="238px" height="64px" xlink:href="http://cdn.sstatic.net/stackoverflow/img/sprites.png"
         preserveAspectRatio="xMinYMin slice"/>

  <!-- Use a CSS clip rectangle to show a small facebook logo from the sprite.  Logo is at 150,1000 with dimensions 19x19.
       Positioned at 100,200 in the SVG (-50+150, -800+1000).  Could also use a clip-path for this. -->
  <image x="-50px" y="-800px" width="238px" height="1073px" xlink:href="http://cdn.sstatic.net/stackoverflow/img/sprites.png"
         clip="rect(200 100 219 119)" />

  <!-- Use a svg viewBox to show the facebook logo from the sprite.
       By setting our viewBox to the bounds of the logo, the renderer will scale it to fit the specified width and height.
       Which in this case is 19x19 - the same size as the sprite. -->
  <svg x="100px" y="300px" width="19px" height="19px" viewBox="150 1000 19 19" version="1.1">
    <image x="0px" y="0px" width="238px" height="1073px" xlink:href="http://cdn.sstatic.net/stackoverflow/img/sprites.png" />
  </svg>

</svg>

【讨论】:

  • ? 你的“将图像嵌入另一个 ”的想法,TY - 对我有用?
猜你喜欢
  • 1970-01-01
  • 2021-06-04
  • 2014-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-10
  • 1970-01-01
相关资源
最近更新 更多