Skip to content

Commit

Permalink
Merge pull request #20 from habibillah/master
Browse files Browse the repository at this point in the history
allow to add custom color
  • Loading branch information
yohangdev authored Feb 12, 2019
2 parents 522987e + 35f1ac2 commit 1751e0e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,9 @@ $avatar->saveAs('path/to/filename', LetterAvatar::MIME_TYPE_JPEG);
``` html
<img src="<?php echo $avatar ?>" />
```

To use static colour or custom colour use `->setColor($background, $foreground);`

``` html
<img src="<?php echo $avatar->setColor('#000000', '#ffffff');?>" alt="">
```
34 changes: 29 additions & 5 deletions src/LetterAvatar.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@ class LetterAvatar
*/
private $imageManager;

/**
* @var string
*/
private $backgroundColor;

/**
* @var string
*/
private $foregroundColor;

/**
* LetterAvatar constructor.
* @param string $name
Expand All @@ -60,6 +70,19 @@ public function __construct(string $name, string $shape = 'circle', int $size =
$this->setSize($size);
}

/**
* color in RGB format (example: #FFFFFF)
*
* @param $backgroundColor
* @param $foregroundColor
*/
public function setColor($backgroundColor, $foregroundColor)
{
$this->backgroundColor = $backgroundColor;
$this->foregroundColor = $foregroundColor;
return $this;
}

/**
* @param string $name
*/
Expand Down Expand Up @@ -103,21 +126,22 @@ private function generate(): \Intervention\Image\Image
$isCircle = $this->shape === 'circle';

$this->nameInitials = $this->getInitials($this->name);
$color = $this->stringToColor($this->name);
$this->backgroundColor = $this->backgroundColor ?: $this->stringToColor($this->name);
$this->foregroundColor = $this->foregroundColor ?: '#fafafa';

$canvas = $this->imageManager->canvas(480, 480, $isCircle ? null : $color);
$canvas = $this->imageManager->canvas(480, 480, $isCircle ? null : $this->backgroundColor);

if ($isCircle) {
$canvas->circle(480, 240, 240, function (CircleShape $draw) use ($color) {
$draw->background($color);
$canvas->circle(480, 240, 240, function (CircleShape $draw) {
$draw->background($this->backgroundColor);
});

}

$canvas->text($this->nameInitials, 240, 240, function (Font $font) {
$font->file(__DIR__ . '/fonts/arial-bold.ttf');
$font->size(220);
$font->color('#fafafa');
$font->color($this->foregroundColor);
$font->valign('middle');
$font->align('center');
});
Expand Down

0 comments on commit 1751e0e

Please sign in to comment.