Как создать прозрачный фон в GD без размытия изображения? - PullRequest
1 голос
/ 01 октября 2019

Я пытаюсь создать круговую диаграмму, которая будет отображать статистику браузера.

Но когда я пытаюсь создать прозрачный фон для диаграммы, текст получается размытым, чем обычный фон.

    define('FONT', "C:/Windows/fonts/Arial.ttf");
    $data = ['edge' => 3, 'ie' => 4, 'firefox' => 12, 'chrome' => 40, 'opera' => 9, 'android' => 18];

    function textWidth($text, $fontSize) {
        $sizes = array_map(function($x){ return $x * .75; }, imagettfbbox($fontSize, 0, FONT, $text));
        return $sizes[6] - $sizes[4];
    }

    asort($data);

    $total = array_sum($data);
    $before = -90;

    $w = 300;
    $h = 300;

    $graph = imagecreatetruecolor($w * 2, $h * 2);

    // this is the part where background blurrs: remove this part to compare
    imagealphablending($graph, false);
    $transparency = imagecolorallocatealpha($graph, 0, 0, 0, 127);
    imagefill($graph, 0, 0, $transparency);
    imagesavealpha($graph, true);
    //part end

    $text_color = imagecolorallocate($graph, 0, 0, 0);

    foreach ($data as $key => $value) {     
        $ratio = 100 / $total * $value;
        $deg = $before + 3.6 * $ratio;

        $color = imagecolorallocate($graph, rand(128,255), rand(128,255), rand(128,255));
        imagefilledarc($graph, $w, $h, $w * 2, $h * 2, $before, $deg, $color, IMG_ARC_PIE);

        $posX = $w + $w * cos(deg2rad($deg - 1.8 * $ratio)) * .75;
        $posY = $w + $w * sin(deg2rad($deg - 1.8 * $ratio)) * .75;

        $ratio = floor($ratio);
        imagettftext($graph, 16, 0, $posX + textWidth($key, 18) / 2, $posY, $text_color, FONT, $key);
        imagettftext($graph, 16, 0, $posX + textWidth($ratio . "%", 18) / 2, $posY + 30, $text_color, FONT, $ratio . "%");

        $before = $deg;
    }

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

Я пытался создать прозрачный фон после рисования каждой части графика, но это не сработало.

Буду признателен за любую помощь. Спасибо!

1 Ответ

0 голосов
/ 08 октября 2019

Вы можете удалить следующую строку:

imagealphablending($graph, false);

Или повторно включить альфа-смешение после настройки прозрачности:

imagealphablending($graph, false);
$transparency = imagecolorallocatealpha($graph, 0, 0, 0, 127);
imagefill($graph, 0, 0, $transparency);
imagealphablending($graph, true); // add this
imagesavealpha($graph, true);

Результат:

non blurry image

...