@@ -12,7 +12,7 @@ final class GenerateSocialShareImage
1212{
1313 const TEXT_X_POSITION = 50 ;
1414
15- const TEXT_Y_POSITION = 150 ;
15+ const TEXT_Y_BASE_POSITION = 90 ;
1616
1717 const TEXT_COLOUR = '#161e2e ' ;
1818
@@ -32,18 +32,32 @@ public function handle(): Response
3232 $ text = wordwrap ($ this ->article ->title (), self ::CHARACTERS_PER_LINE );
3333
3434 return Cache::remember (
35- 'articleSocialImage- ' . $ this ->article ->id ,
35+ 'articleSocialImage- ' . $ this ->article ->id ,
3636 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+ )
4449 ->toPng ()
45- )->header ('Content-Type ' , 'image/png ' )
50+ )
51+ ->header ('Content-Type ' , 'image/png ' )
4652 ->header ('Cache-Control ' , 'max-age=86400, public ' )
4753 );
4854 }
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+ }
4963}
0 commit comments