2010-09-09 10 views
6

estoy usando imagettftext para hacer un gráfico de barras y en la parte superior de cada barra Quiero poner el valor .PHP alineación central GD ttftext

tengo el siguientes variables para cada barra (que en realidad son rectángulos)

$x1 $y1 $x2 $y2 $imagesx $imagesy $font_size

Además, el tamaño de fuente debería disminuir a medida que la la longitud de la cuerda aumenta

alt text

+1

Boy, usted se encontrará con un poco de trabajo! ¿* Tiene * que ser PHP? Hay bibliotecas de trazado de javascript tan agradables (y ya hechas) por ahí ... –

+0

Estoy haciendo una biblioteca de PHP así que ... –

+0

Sería bueno tener el código "haciendo un gráfico de barras" para la muestra, ¿puedes publicarlo? – Otar

Respuesta

11

Hazlo así. Recuerde que debe colocar el archivo de fuentes "arial.ttf" en el directorio actual:

<?php 
// Create a 650x150 image and create two colors 
$im = imagecreatetruecolor(650, 150); 
$white = imagecolorallocate($im, 255, 255, 255); 
$black = imagecolorallocate($im, 0, 0, 0); 

// Set the background to be white 
imagefilledrectangle($im, 0, 0, 649, 149, $white); 

// Path to our font file 
$font = './arial.ttf'; 

//test it out 
for($i=2;$i<10;$i++) 
    WriteTextForMe($im, $font, str_repeat($i, $i), -140 + ($i*80), 70 + rand(-30, 30), -160 + (($i+1)*80), 150, $black); 

//this function does the magic 
function WriteTextForMe($im, $font, $text, $x1, $y1, $x2, $y2, $allocatedcolor) 
{ 
    //draw bars 
    imagesetthickness($im, 2); 
    imagerectangle($im, $x1, $y1, $x2, $y2, imagecolorallocate($im, 100,100,100)); 

    //draw text with dynamic stretching 
    $maxwidth = $x2 - $x1; 
    for($size = 1; true; $size+=1) 
    { 
     $bbox = imagettfbbox($size, 0, $font, $text); 
     $width = $bbox[2] - $bbox[0]; 
     if($width - $maxwidth > 0) 
     { 
      $drawsize = $size - 1; 
      $drawX = $x1 + $lastdifference/2; 
      break; 
     } 
     $lastdifference = $maxwidth - $width; 
    } 
    $size--; 
    imagettftext($im, $drawsize, 0, $drawX, $y1 - 2, $allocatedcolor, $font, $text); 
} 

// Output to browser 
header('Content-type: image/png'); 

imagepng($im); 
imagedestroy($im); 
?> 

Utiliza imagettfbbox función para obtener el ancho del texto, a continuación, los bucles sobre el tamaño de fuente para conseguir el tamaño correcto, lo centra y lo muestra.

Así, se muestra la siguiente información:

alt text

2

Puede calcular el centro de su texto mediante el uso de PHP imagettfbbox-function:

// define text and font 
$text = 'some bar label'; 
$font = 'path/to/some/font.ttf'; 

// calculate text size (this needs to be adjusted to suit your needs) 
$size = 10/(strlen($text) * 0.1); 

// calculate bar center 
$barCenter = $x1 + ($x2 - $x1)/2; 

// calculate text position (centered) 
$bbox = imagettfbbox($size, 0, $font, $text); 
$textWidth = $bbox[2] - $bbox[0]; 
$positionX = $textWidth/2 + $barCenter; 
$positionY = $y1 - $size; 

EDIT: Actualizado el código para hacer todo el trabajo por usted.

+0

¿Cómo * exactamente * lo usaría para obtener el lugar para escribirlo por lo que se centra –

+0

Edité mi publicación en consecuencia. El código calcula la posición del eje x del texto dado con la alineación central '$ positionX'. – jwueller

+0

Hmm, déjame volver a escribir la pregunta –

Cuestiones relacionadas