gpt4 book ai didi

php - 使用 gd 调整字体大小和填充以创建动态条形图

转载 作者:行者123 更新时间:2023-12-03 00:54:03 24 4
gpt4 key购买 nike

受到此启发code ,我正在尝试创建一个简单的条形图,能够动态创建、调整条形和文本的大小,具体取决于 $data$height$weight :

<?php

$width = 300;
$height = 200;

$font_path = getenv('WINDIR') . DIRECTORY_SEPARATOR . "Fonts" . DIRECTORY_SEPARATOR;
$font = 'arial.ttf';

$data = ['jan'=>30,'fev'=>40,'mar'=>90,'apr'=>77,
'mai'=>33, 'jun'=>44, 'bigggggggg' => 80];

$columns = count($data);
$padding = ($width+$height)/100;

$column_width = $width / $columns;

$image = imagecreate($width, $height);
$gray = imagecolorallocate($image, 0xcc, 0xcc, 0xcc);
$black = imagecolorallocate($image, 0, 0, 0);
$gray_lite = imagecolorallocate($image, 0xee, 0xee, 0xee);
$gray_dark = imagecolorallocate($image, 0x7f, 0x7f, 0x7f);
$white = imagecolorallocate($image, 0xff, 0xff, 0xff);

imagefilledrectangle($image, 0, 0, $width, $height, $white);
$maxv = max($data);

$array_values = array_values($data);
$array_keys = array_keys($data);
for ($i = 0; $i < $columns; $i++) {

$font_size = ($height / 100) * $padding;
$column_height = ($height / 100) * (( $array_values[$i] / $maxv) * 100);
$string = $array_keys[$i];

$x1 = $i * $column_width;
$y1 = $height - $column_height;
$x2 = (($i + 1) * $column_width) - $padding;
$y2 = $height - ($padding*4);
$maxChars = ($font_size * 2) / $padding;

if (strlen($string) > ($maxChars)) {
$string = substr($string, 0, $maxChars) . '...';
}

imagefilledrectangle($image, $x1, $y1, $x2, $y2, $gray);
imagettftext($image, $font_size, 0, $x1, $y2+$font_size+$padding, $black, $font_path.$font,
$string);

imageline($image, $x1, $y1, $x1, $y2, $gray_lite);
imageline($image, $x1, $y2, $x2, $y2, $gray_lite);
imageline($image, $x2, $y1, $x2, $y2, $gray_dark);
}

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

使用 300x200 没问题:

enter image description here

但使用 600x400:

enter image description here

我可以做什么来解决这个问题?

最佳答案

只有字体大小计算可以修复早期代码:

$font_size = ($height / 100) * $padding;           //Changing this line
$column_height = ($height / 100) * (( $array_values[$i] / $maxv) * 100);
$string = $array_keys[$i];

$x1 = $i * $column_width;
$y1 = $height - $column_height;
$x2 = (($i + 1) * $column_width) - $padding;
$y2 = $height - ($padding*4);
$maxChars = ($font_size * 2) / $padding;

动态更改后,如下所示:

$column_height = ($height / 100) * (( $array_values[$i] / $maxv) * 100);
$string = $array_keys[$i];

$x1 = $i * $column_width;
$y1 = $height - $column_height;
$x2 = (($i + 1) * $column_width) - $padding;
$y2 = $height - ($padding*4);
$font_size = ($x2 - $x1) / 4; //Changed line and location
$maxChars = ($font_size * 2) / $padding;

除了此更改之外,无需执行任何操作。

关于php - 使用 gd 调整字体大小和填充以创建动态条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58824048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com