PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 10, 2022

[FIXED] How to control text alignment for text generated using `imagettftext()`?

 October 10, 2022     gd, imagettftext, php     No comments   

Issue

Using the imagettftext function from the PHP GD library, one can only draw text that is left-aligned onto an image. At least so it would seem, perhaps I'm missing something.

How can I control the alignment of the text drawn onto an image? i.e. left / center / right (/ justified - not necessary, but useful)

I should mention that the alignment is visible when the drawn text contains multiple lines (e.g. "bla bla bla/nAnd another line of bla.").


Solution

with imagettftext() you're not writing into some kind of "box" but just at the given coordnates. to alingn the text properly, you'll have to calculate the correct coordinates to make it "look like" it's right-aligned or centered.

to do so, you can use imagettfbox() to get the size of your text - the rest is simple math:

  • to right-align add [textarea-width]-[textwidth] to your X-coordinate
  • to center add ([textarea-width]-[textwidth]) / 2 to your X-coordinate

(*textarea = the area you want to write the text at in your image - it's size should be known to you)



Answered By - oezi
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing