PHP GD how to draw text over a line

筅森魡賤 提交于 2019-12-19 06:20:42

问题


The final output should be like image(HELLO WORLD):

Here is what i am doing:-

$im = imagecreate(400,400); 

$txtcol = imagecolorallocate($im, 0xFF, 0x00, 0x00);

$size = 20;

$txt = 'DUMMY TEXT';

$font = './font/Capriola-Regular.ttf';

/*two points for base line*/

$x1 = 50; $x2 = 300; 

$y1 = 150; $y2 = 170;

/*bof finding line angle*/

$delta_x = $x2-$x1;

$delta_y = $y2-$y1;

$texangle = (rad2deg(atan2($delta_y,$delta_x)) * 180 / M_PI)-360;

/*eof finding the line angle*/


imageline($im,$x1,$y1,$x2,$y2,$txtcol); //Drawing line

imagettftext($im, $size, $texangle, $x1, $y1, $txtcol, $font, $txt); // Drawing text over line at line's angle

And current output is like:

Can anybody tell whats the wrong with my code?

THanks


回答1:


Ok, been playing around. Try replacing:

$texangle = (rad2deg(atan2($delta_y,$delta_x)) * 180 / M_PI)-360;

With:

$texangle = (atan2($delta_y,$delta_x) * -180 / M_PI)-360;

Output with your values:

Output with other values:




回答2:


2 thoughts, can't test right now.

  1. Where is 0 (x=1, y=0) or (x=0, y=1). It seems your text is off by 90 degrees which usually means that your assuming 0 is directly right, when maybe it's directly up or vice versa.

  2. (rad2deg(atan2($delta_y,$delta_x)) * 180 / M_PI)-360; are you doing double work here? rad2deg converts from radians to degrees. 180 / M_PI is also a conversion from radians to degrees.




回答3:


This is not the exact thing what you may be looking for, but i believe it will help you

$im = imagecreate(400,400); 

$txtcol = imagecolorallocate($im, 0xFF, 0xFF, 0x00);

$size = 20;

$txt = 'DUMMY TEXT';

$font = 'Capriola-Regular.ttf';

/*two points for base line*/

$x1 = 70; $x2 = 170; 

$y1 = 140; $y2 = 240;

/*bof finding line angle*/

$delta_x = $x2-$x1;

$delta_y = $y2-$y1;

$texangle = (rad2deg(atan2($delta_y,$delta_x)) * 180 / M_PI)-360;

/*eof finding the line angle*/


imageline($im,$x1,$y1,$x2,$y2,'0xDD'); //Drawing line
imagettftext($im, $size, -45, $x1, $y1-10, '0xDD', $font, $txt); // Drawing text over line at line's angle

header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);

values are hard coded. Here the angle is given as -45 and for that angle if you want your text to appear above line you have to reduce the value from initial Y position of your line. And you will have to write code to calculate the angle with line's x1,x2y1,y2



来源:https://stackoverflow.com/questions/14894049/php-gd-how-to-draw-text-over-a-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!