SVG масштабируется в пределах SVG в определенных местах - PullRequest
0 голосов
/ 14 сентября 2011

Я новичок в сложных SVG и работаю над чем-то, и мне нужна помощь.У меня есть пара файлов SVG, которые уже правильно отформатированы с содержимым .. линиями, прямоугольниками, текстом и т. Д. Они нарисованы с простыми X =, Y =, X1 =, Y1 = и основаны только на целых числах.Оригинальный SVG был разработан для печати, а позиции x / y были установлены на основе печати с разрешением 300 точек на дюйм.

Так что это существует с парой SVG, происходящей из других источников, и я пытаюсь объединиться в новый единый SVGдокумент.Итак, один из этих элементов мне нужно поместить в положение (x, y), основанное на дюймах или сантиметрах (из того, что я читал до сих пор), но мне также нужно, чтобы они соответствовали определенному размеру ... скажем2 в высоту, 3,4 дюйма в ширину.

Поскольку исходный SVG был основан только на целых числах и без ориентации на «дюймы», что я могу сделать ... или, как он может масштабироваться.

Без правильного синтаксиса SVG,вот в основном некоторые из деталей.

SVG1 имеет общую площадь прямоугольника x / y от 0,0 до 476 100 SVG2 имеет общую площадь прямоугольника x / y от 0,0 до 273,24

Новый SVG должен быть 4 "на 6"

Пример: в положении 1/4 "вниз, 1" в поперечном направлении сверху, мне нужно вставить SVG1, и хотя он 476x100, ему нужночтобы быть масштабированным в область около 1/2 "в высоту х 3" в ширину.

Точно так же, в положении 2,8 "вниз, 1,75" в поперечнике, мне нужно вставить SVG2, и его размер должен быть около 2 "высокий и 2.5 "в ширину как максимальная площадь.

Масштабируется да, но для того, чтобы его не перекосить, им нужно сохранить исходные пропорции и не обрезать.Если я смогу получить базовое понимание, я смогу настроить окончательные измерения, просто не знаю, как получить инфраструктуру этой работы.

Спасибо.

1 Ответ

1 голос
/ 15 сентября 2011

Я наконец-то получил его после долгих тренировок, на тот случай, если кто-то заинтересован и относительно нов в SVG, как и я. Как и в этом вопросе, у меня были несколько предварительно сгенерированных выходных файлов SVG, которые имеют свои настройки X, Y Height, Width, основанные на числовом значении, без контекста в дюймах, сантиметрах и т. Д., Но я должен был соответствовать данному X дюйм по Y-дюймовому диапазону.

Итак, я узнал о теге «defs», который похож на объявление переменной, которая впоследствии может быть использована как «поместить эту вещь ЗДЕСЬ» в более позднее тело SVG. На вершине SVG я смог указать нужные размеры. Затем, используя тег «g» для группировки, я могу численно позиционировать что-либо в заданную позицию x, y. Затем, в рамках этого, я сделал еще одну «g», чтобы применить масштабирование «переменной», как объявлено в разделе «defs» (поскольку элемент «g» не может иметь два тега «transform» внутри него).

Я придумал что-то похожее на приведенное ниже, и надеюсь, что подробные комментарии помогут другим в их исследованиях, посвященных 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">

    <!-- Explicitly define the SVG window area as 4 inches by 6 inches -->
    <svg xmlns="http://www.w3.org/2000/svg"
         xmlns:xlink="http://www.w3.org/1999/xlink"
         width="4in" height="6in" >

    <!-- Add some styles, fonts etc for line drawing, labels and data -->
    <style type="text/css" >
        <![CDATA[

            line.Black
            {   stroke:RGB(0,0,0);
                stroke-width:2;
            }

            text.Hdr
            { 
                font-family: Arial;
                font-size:x-small;
                stroke: #000000;
                stroke-width:.4;
            }

            text.Data
            {
                font-family: Courier New;
                font-size:normal;
                stroke: #000000;
                stroke-width:.5;
            }
        ]]>
    </style>


    <!-- all these "defs" are zero-based position for their own content
        and will be speicifcally placed where needed via "g" tags.
        The simple "id" name will be used as an "insert <something> here" -->
    <defs>
        <!-- Below will come from actual data from system
            The "ID" is what becomes the "variable" that is later
            used later in the SVG as the "put me here" -->
        <g id="DataOneElement" >
            <text class="Data">SOME TEXT DATA</text>
        </g>

        <!-- This partial linear barcode generated somewhere else 
            Notice these are just integer positions, and nothing
            to do with specific "inches" measurements.  Also, they
            start at position 0,0 and go however large they need.
            When applied with the "g" positioning, thats where it
            starts, then gets scaled from there if needed bigger/smaller -->
        <g id="DataPartialBarCode" >
            <rect x="0" y="0" width="1" height="50" />
            <rect x="4" y="0" width="1" height="50" />
            <rect x="6" y="0" width="3" height="50" />
            <rect x="10" y="0" width="3" height="50" />
            <rect x="14" y="0" width="1" height="50" />
            <rect x="16" y="0" width="3" height="50" />
            <rect x="20" y="0" width="3" height="50" />
            <rect x="24" y="0" width="1" height="50" />
            <rect x="26" y="0" width="1" height="50" />
            <rect x="30" y="0" width="1" height="50" />
            <rect x="32" y="0" width="1" height="50" />
            <rect x="34" y="0" width="1" height="50" />
            <rect x="38" y="0" width="3" height="50" />
        </g>

        <!-- Actual data generated from AMS to populate these too.
            Notice here too, the entire address starts as position 0,0 -->
        <g id="SampleAddress" >
            <text class="Data" x="0" y="0">Some Person's Name</text>
            <text class="Data" x="0" y="17">First Address Line</text>
            <text class="Data" x="0" y="30">Another Address</text>
            <text class="Data" x="0" y="43">3rd Address line</text>
            <text class="Data" x="0" y="56">And Testing for longer address content</text>
        </g>

        <!-- another bar code that will generated -->
        <g id="AnotherBarCode" >
            <rect x="0" y="0" width="1" height="70" />
            <rect x="4" y="0" width="1" height="70" />
            <rect x="6" y="0" width="3" height="70" />
            <rect x="10" y="0" width="3" height="70" />
            <rect x="14" y="0" width="1" height="70" />
            <rect x="16" y="0" width="3" height="70" />
            <rect x="20" y="0" width="1" height="70" />
            <rect x="24" y="0" width="1" height="70" />
            <rect x="26" y="0" width="1" height="70" />
            <rect x="28" y="0" width="3" height="70" />
            <rect x="32" y="0" width="1" height="70" />
            <rect x="36" y="0" width="1" height="70" />
            <rect x="38" y="0" width="3" height="70" />
            <rect x="42" y="0" width="3" height="70" />
            <rect x="46" y="0" width="1" height="70" />
        </g>
    </defs>

    <!-- Now, starting the drawing of the SVG...
        Border around entire box drawing area 
        Notice these are in specific INCH dimensions... -->
    <line class="Black" x1="0in" y1="0in" x2="4in" y2="0in" />
    <line class="Black" x1="0in" y1="0in" x2="0in" y2="6in" />
    <line class="Black" x1="4in" y1="0in" x2="4in" y2="6in" />
    <line class="Black" x1="0in" y1="6in" x2="4in" y2="6in" />


    <!-- Translate is Across then Down from the top/left corner of SVG -->
    <!-- Translate is NOT based on inch, cm, or other measurements
         so you may have to tweak these numbers -->
    <g transform="translate( 100 20 ) ">
        <!-- Now, take whatever we are providing and scale it within the area.
            In this case, scale the ENTIRE "g" object to 1.5 its original size -->
        <g transform="scale(1.75)">
            <!-- This is where the "defs" variable declaration comes 
                in, as looking at the "g" tag by the ID name -->
            <use xlink:href="#DataOneElement" />
        </g>
    </g>

    <!-- and now the partial barcode "defs" variable -->
    <g transform="translate( 20 23 ) ">
        <!-- In this case, scale the width by 115% and the height by 95% -->
        <g transform="scale( 1.15 .95 )">
            <use xlink:href="#DataPartialBarCode" />
        </g>
    </g>


    <!-- Any other specific lines within the area -->
    <line class="Black" x1="0in" y1=".8in" x2="4in" y2=".8in" />

    <!-- Now, just insert the "defs" from above at a scale that will still be readable.
        Cool thing, the entire address is considered a single element here. -->
    <g transform="translate(20 97)">
        <g transform="scale(.7)">
            <use xlink:href="#SampleAddress" />
        </g>
    </g>


    <!-- We can even show the address AGAIN, scaled differently elsewhere. -->
    <g transform="translate(2 250)">
        <g transform="scale(1.3)">
            <use xlink:href="#SampleAddress" />
        </g>
    </g>

    <!-- Another line and then barcode-->
    <line class="Black" x1="0in" y1="1.55in" x2="4in" y2="1.55in" />

    <g transform="translate( 175 175 ) ">
        <!-- Scale this barcode 100% wide, but only 70% height -->
        <g transform="scale(1 .7)">
            <use xlink:href="#AnotherBarCode" />
        </g>
    </g>
</svg>
...