【问题标题】:How to create an SVG with support of more than one Pixel Ratio?如何创建支持多个像素比的 SVG?
【发布时间】:2012-12-12 21:37:08
【问题描述】:

我想创建使用 元素的与分辨率无关的 SVG。是否可以测试用户代理的实际像素比?请看示例:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="640" height="480">
    <defs>
        <pattern id="test" patternUnits="userSpaceOnUse"
            x="0" y="0" width="130" height="100"
            viewBox="0 0 130 100" >
            <IF PIXEL RATIO = 2>
                <image xlink:href="test_2x.png" id="svg_1" height="100" width="130" y="0" x="0"/>
            <ELSE>
                <image xlink:href="test.png" id="svg_1" height="100" width="130" y="0" x="0"/>
            <END IF>
        </pattern> 
    </defs>
    <rect id="rectangle" stroke="rgb(29, 29, 255)"  fill="url(#test)" x="50" y="47" width="320" height="240" />
</svg>

我只在the documentation 中找到了Switch Element,但它似乎没有多大帮助,因为没有“视网膜显示”功能。或者有吗? :)

【问题讨论】:

    标签: svg retina-display resolution-independence pixel-ratio


    【解决方案1】:

    您可以使用 CSS 媒体选择器来检测视网膜显示。使用 display 属性,您可以根据设备打开和关闭图像。

    我手头没有 Apple Retina 设备进行测试,但我认为 something like this 应该可以工作:

    <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="640" height="480">
      <style type="text/css">
        @media all {
          #test_2x_png {display:none}
        }
        @media (-webkit-min-device-pixel-ratio: 2) {
          #test_png    {display:none;}
          #test_2x_png {display:inline;}
        }
      </style>
      <defs>
        <pattern id="test" patternUnits="userSpaceOnUse"
            x="0" y="0" width="130" height="100"
            viewBox="0 0 130 100" >
              <image xlink:href="test_2x.png" height="100" width="130" y="0" x="0" id="test_2x_png"/>
              <image xlink:href="test.png" height="100" width="130" y="0" x="0" id="test_png"/>
        </pattern> 
      </defs>
      <rect id="rectangle" stroke="rgb(29, 29, 255)"  fill="url(#test)" x="50" y="47" width="320" height="240" />
    </svg>
    

    【讨论】:

    • 啊,这很聪明。我放弃了媒体查询,因为它们不允许更改 xlink 引用,但这是一个非常漂亮的解决方案。
    • 这太好了,谢谢!唯一的一点是 @media all 必须是第一个,但除此之外,您的解决方案是完美的。
    • 谢谢,我会在我的回答中解决这个问题,以便其他人可以更好地利用它。
    • 这种技术很有前途,但它不适用于典型的高 dpi 用例。如果您查看网络检查器,您会看到无论您是否在视网膜屏幕上,这两个图像都已下载。将图像元素(或其父元素)的显示设置为无并不会像使用 css 背景图像那样阻止图像的下载,它只会切换显示的图像。由于无论如何您都在加载两者,如果只是质量问题,没有理由不只使用视网膜分辨率。
    • @Dwight 这当然是一个非常有效的观点。 JavaScript 会有所帮助,但对于 HTML &lt;img&gt; 元素使用的 SVG,这对 AFAIK 不起作用。
    猜你喜欢
    • 1970-01-01
    • 2022-07-18
    • 2011-06-20
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2017-09-29
    • 2012-03-10
    相关资源
    最近更新 更多