Add gradient

This commit is contained in:
Philipp Lang 2022-11-18 12:00:00 +01:00
parent cf562f8a59
commit e00bdc1277
4 changed files with 96 additions and 0 deletions

19
src/Degree.php Normal file
View File

@ -0,0 +1,19 @@
<?php
namespace Zoomyboy\Gradient;
class Degree
{
public function __construct(public int $value)
{
}
public static function from(int $degree): self
{
if ($degree >= 0 && $degree <= 360) {
return new self($degree);
}
throw Exception('Degree must be between 0 and 360');
}
}

50
src/GradientImage.php Normal file
View File

@ -0,0 +1,50 @@
<?php
namespace Zoomyboy\Gradient;
use GdImage;
class GradientImage
{
public function generate(int $image_width, int $image_height, string $from, string $to, Degree $degree, Prop $prop = Prop::LINEAR): void
{
$from = $this->toRgb($from);
$to = $this->toRgb($to);
$image = imagecreatetruecolor($image_width, $image_height);
$image = $this->makeGradient($image, $from, $to, $prop->calculatorCallback());
$image = imagerotate($image, 360 - $degree->value, 0);
imagepng($image, 'image.png');
imagedestroy($image);
}
public function toRgb(string $hexColor): RgbColor
{
$hexColor = substr($hexColor, 1);
$colors = collect(str_split($hexColor, 2))
->map(fn ($hex) => hexdec($hex))
->toArray();
return new RgbColor(...$colors);
}
private function makeGradient(GdImage $image, RgbColor $from, RgbColor $to, callable $calculator): GdImage
{
$image_width = imagesx($image);
$image_height = imagesy($image);
for ($i = 0; $i < $image_height; ++$i) {
$percent = $calculator($i, $image_height);
$color_r = (int) floor(($from->r - $to->r) * $percent) + $to->r;
$color_g = (int) floor(($from->g - $to->g) * $percent) + $to->g;
$color_b = (int) floor(($from->b - $to->b) * $percent) + $to->b;
$color = imagecolorallocate($image, $color_r, $color_g, $color_b);
imageline($image, 0, $i, $image_width, $i, $color);
}
return $image;
}
}

17
src/Prop.php Normal file
View File

@ -0,0 +1,17 @@
<?php
namespace Zoomyboy\Gradient;
enum Prop
{
case LINEAR;
case WAVE;
public function calculatorCallback(): callable
{
return match ($this) {
static::LINEAR => fn ($i, $height) => $i / $height,
static::WAVE => fn ($i, $height) => abs(($i / $height) - 0.5),
};
}
}

10
src/RgbColor.php Normal file
View File

@ -0,0 +1,10 @@
<?php
namespace Zoomyboy\Gradient;
class RgbColor
{
public function __construct(public int $r, public int $g, public int $b)
{
}
}