php取文学在图片居中,用PHP居中imagestring()?

我正在尝试为我的欢迎页面创建图像,并希望将字符串以动态方式居中,否则使用诸如John和Alexandra之类的不同用户名就太糟糕了.

header("Content-type: image/png");

$string1 = "Hello!";

$string2 = "Welcome to our website!";

$srting3 = "$username";

$font1 = 5;

$font2 = 3;

$font3 = 3;

$img_w = 240;

$img_h = 64;

$image = imagecreatetruecolor ($img_w, $img_h);

$white = imagecolorallocate ($image, 255,255,255);

$black = imagecolorallocate ($image, 0, 0, 0);

imagefill($image, 0, 0, $white);

imagestring ($image, $font1, 110, 0, $string1, $black);

imagestring ($image, $font2, 60, 20, $string2, $black);

imagestring ($image, $font3, 105, 40, $string3, $black);

imagepng ($image);

imagedestroy($image);

解决方法:

尝试使用imagefontwidth()函数获取每个字符的宽度,并将其与strlen($string)相乘,也可以使用imagefontheight()来更新高度.

header("Content-type: image/png");

$string1 = "Hello!";

$string2 = "Welcome to our website!";

$srting3 = "$username";

$font1 = 5;

$width1 = imagefontwidth($font1) * strlen($string);

$height1 = imagefontheight($font1);

$font2 = 3;

$width2 = imagefontwidth($font2) * strlen($string2);

$height2 = imagefontheight($font2);

$font3 = 3;

$width3 = imagefontwidth($font3) * strlen($string3);

$height3 = imagefontheight($font3);

$img_w = 240;

$img_h = 64;

$image = imagecreatetruecolor ($img_w,$img_h);

$white = imagecolorallocate ($image,255,255,255);

$black = imagecolorallocate ($image,0,0,0);

imagefill($image,0,0,$white);

imagestring ($image,$font1,($img_w/2)-($width1/2), 0,$string1,$black);

imagestring ($image,$font2,($img_w/2)-($width2/2), $height1,$string2,$black);

imagestring ($image,$font3,($img_w/2)-($width3/2), $height1+$height2,$string3,$black);

imagepng ($image);

imagedestroy($image);

标签:css,php

来源: https://codeday.me/bug/20191121/2054991.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值