@@ -12,7 +12,7 @@ final class GenerateSocialShareImage
12
12
{
13
13
const TEXT_X_POSITION = 50 ;
14
14
15
- const TEXT_Y_POSITION = 150 ;
15
+ const TEXT_Y_BASE_POSITION = 90 ;
16
16
17
17
const TEXT_COLOUR = '#161e2e ' ;
18
18
@@ -32,18 +32,32 @@ public function handle(): Response
32
32
$ text = wordwrap ($ this ->article ->title (), self ::CHARACTERS_PER_LINE );
33
33
34
34
return Cache::remember (
35
- 'articleSocialImage- ' . $ this ->article ->id ,
35
+ 'articleSocialImage- ' . $ this ->article ->id ,
36
36
now ()->addDay (),
37
- fn () => response (
38
- $ image ->read (resource_path ('images/ ' .self ::TEMPLATE ))
39
- ->text ($ text , self ::TEXT_X_POSITION , self ::TEXT_Y_POSITION , function ($ font ) {
40
- $ font ->file (resource_path ('fonts/ ' .self ::FONT ));
41
- $ font ->size (self ::FONT_SIZE );
42
- $ font ->color (self ::TEXT_COLOUR );
43
- })
37
+ fn () => response (
38
+ $ image ->read (resource_path ('images/ ' . self ::TEMPLATE ))
39
+ ->text (
40
+ $ text ,
41
+ self ::TEXT_X_POSITION ,
42
+ self ::calculateTextYPosition ($ text ),
43
+ function ($ font ) {
44
+ $ font ->file (resource_path ('fonts/ ' . self ::FONT ));
45
+ $ font ->size (self ::FONT_SIZE );
46
+ $ font ->color (self ::TEXT_COLOUR );
47
+ }
48
+ )
44
49
->toPng ()
45
- )->header ('Content-Type ' , 'image/png ' )
50
+ )
51
+ ->header ('Content-Type ' , 'image/png ' )
46
52
->header ('Cache-Control ' , 'max-age=86400, public ' )
47
53
);
48
54
}
55
+
56
+ private function calculateTextYPosition (string $ text ): int
57
+ {
58
+ $ noOfLinesInText = substr_count ($ text , "\n" );
59
+
60
+ return self ::TEXT_Y_BASE_POSITION
61
+ + ((self ::FONT_SIZE * $ noOfLinesInText ) - $ noOfLinesInText );
62
+ }
49
63
}
0 commit comments