2011-05-09 29 views
7

在我的網站我允許用戶創建文本行的照片,他們指定畫在畫面配件文本框

目前我使用的是ImageMagick的轉換 - 我指定SVG模板,讓轉換完成剩下的

這裏是代碼的一部分,負責在畫面

<text text-anchor="middle" x="50%%" y="%s" 
     font-family="Times New Roman" font-size="55" 
     style="fill:rgb(255,255,255);"> 
    %s 
    </text> 

我的問題是,如果用戶提供了非常長的字符串,該文本不適合在圖像輸出文本。

我想要文本自動調整大小,如果它不適合圖片更小的字體。有可能使用svg模板嗎?如果不是,可能是其他解決方案

+0

參見:http://stackoverflow.com/questions/2938779/svg-scaling-text-to-fit-container – 2012-08-04 17:32:18

回答

2

通過放棄SVG和做與ImageMagick的轉換和MVG模板

一切就迎刃而解了這裏的情況下,任何人的追求相似

腳本是把圖像和畫布上標題的東西簡化的腳本示例。標題與單獨的convert命令創建,保存爲臨時文件,然後放入畫布

#!/bin/sh 

TEMPLATE=" 
push graphic-context 
viewbox 0 0 600 600 
affine 1 0 0 1 0.0 0.0 
push graphic-context 
fill 'rgb(0,0,0)' 
rectangle 0,0 600,600 
pop graphic-context 
push graphic-context 
image Over 38,38 338,338 '%s' 
pop graphic-context 
push graphic-context 
image Over 36,400 529,55 '%s' 
pop graphic-context 
pop graphic-context 
"; 

#1. creating label fitting specified proportions 
#2. converting mvg template to jpeg image (and trimming it in process) 
#3. removing temp file with label 

convert -size 529x55 -background black -family "Times New Roman" -gravity center -fill white label:"$2" "tmp/$1title.jpg" && printf "$TEMPLATE" "images/$1.jpg" "tmp/$1title.jpg" | convert mvg:- -trim +repage -bordercolor black -border 36 "images/$1converted.jpg" && rm "tmp/$1title.jpg" 

#script parameters: $1 is image id, $2 is title text 
4

您可以在SVG模板中添加一個腳本,該腳本在SVG加載時調用並使用getComputedTextLength()調整字體大小。這有點冒險的解決方案,但它似乎工作。

下面是一個快速示例,它在其中繪製一個框和一些文本。不管文件多長時間,文本都應該調整大小(至少指向點):

要在SVG加載時調用代碼,請在SVG中包含onload =「int(evt)」標籤。

<?xml version="1.0" encoding="UTF-8" standalone="no"?> 
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> 
<svg xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" 
    width="400" height="80" 
    onload="init(evt)"> 

然後實際的腳本:

<script type="text/ecmascript"> 
    <![CDATA[ 

    function init(evt) 
    { 
     if (window.svgDocument == null) 
     { 
      svgDocument = evt.target.ownerDocument; 
     } 

     maximum_length = 300; 
     my_text = svgDocument.getElementById('text-to-resize'); 

     for (var font_size=55; font_size>0; font_size--) 
     { 
      if(my_text.getComputedTextLength() < maximum_length){break;} 
      my_text.setAttributeNS(null, "font-size", font_size); 
     } 

    } 

    ]]> 
    </script> 

我只是用一個for循環遞減字體大小直到文本長度小於規定的最大值;我相信有更好的方法來調整文本的大小。

最後實際文本和框:

<rect id="rect1" x="20" y="10" width="320" height="50" fill="white" stroke="black"/> 
<text id="text-to-resize" 
     text-anchor="middle" 
     x="170" y="50" 
     font-family="Times New Roman" font-size="55"> 
whatever text 
</text> 
</svg> 

如果您更改文本,字體大小應改變,使其適合箱內。您可能需要更改x和y值以正確地居中文本。

+1

啊,這將是一個很好的解決方案,但不幸的是imagemagick轉換不執行ecmascript,同時將svg轉換爲jpg :( – 2011-05-10 15:46:22

+0

哦,這太遺憾了,我不知道如何做到這一點,沒有Ecmascript。 – 2011-05-10 16:47:20