现在很多新闻网站的首页都有今日头条新闻,一般都是采用图片的形式来体现,美观漂亮大方,图片文字样式多种多样,这完全是文字无法相比的,虽然文字可以控制大小和颜色,但是无法做到那么细致,和控制文字的字体,类似这样的效果:
因此我们这里修改dedecms的代码,让它根据我们的字体需求来生成类似今日头条新闻的图片样式,实现图片替代文字的头条新闻效果。
第一步:打开\include\extend.func.php文件,在最后一行加上一个PHP类,是用来控制图片样式的
class DeDeTitle{ var $text= '网站头条'; var $bg= '#FFFFFF'; var $color= '#9c1000'; var $width=860; var $height=45; var $size=35; var $font; var $path; function __csetruct($t) { if ($t) { $this ->text=$t; } $this ->font=DEDEINC.'/data/fonts/STXINGKA.TTF'; } function DeDeTitle($t) { $this ->__csetruct($t); } function TextConv(){ global $cfg_soft_lang; if ($cfg_soft_lang!= 'utf-8') { return gb2utf8($this->text); } return $this->text; } function C($color, $rgb) { if (strlen( $color)==4) { for ($i=1; $i<4; $i++) { $str .=str_repeat( $color[ $i],2); } $color ='#'. $str; } switch ($rgb) { case 'R': returnhexdec( substr( $color,1,2)); case 'B': returnhexdec( substr( $color,3,2)); case 'G': returnhexdec( substr( $color,5,2)); } } function Titlepath(){ global $cfg_medias_dir; $name =strtotime( date( 'y-m-dH:i:s')). '.gif'; $path ='/uploads/title/'; if (!is_dir( $path)) { CreateDir( $path );} return $path. $name; } function Show(){ if (!file_exists(DEDEROOT. $this->Titlepath())) { $this ->Make();} global $cfg_cmsurl; return '<imgsrc="'. $cfg_cmsurl. $this->Titlepath(). '"/>'; } function Make(){ $image =imagecreatetruecolor($this->width, $this->height); $bg =ImageColorAllocate($image, $this->C( $this->bg, 'R'), $this->C( $this->bg, 'B'), $this->C( $this->bg, 'G')); $color =ImageColorAllocate($image, $this->C( $this->color, 'R'), $this->C( $this->color, 'B'), $this->C( $this->color, 'G')); ImageFilledRectangle( $image ,0,0,$this->width, $this->height, $bg); imagettftext( $image ,$this->size,0, $this->size/2,( $this->height+ $this->size)/2, $color, $this->font, $this->TextConv()); imagegif( $image ,DEDEROOT.$this->Titlepath()); imagedestroy( $image );} }
注意,这里有两个地方需要注意
1头条图片字体的设置,$this->font=DEDEINC.'/data/fonts/STXINGKA.TTF';您可以把需要的字体样式文件放到这个目录下,并且命名为STXINGKA.TTF,只要字体名字保持一致即可。
2头条图片命名和保存路径
$name=strtotime(date('y-m-dH:i:s')).'.gif';以当前时间命名
$path='/uploads/title/';保存路径在默认的/uploads/title/文件夹下面
第二步:修改模板,在需要生成图片标题的模板里插入以下代码
{dede:arclist row ='1' titlelen= '40' flag= 'h'} < a href= "[field:arcurl/]" title= "[field:title/]" > [field:title runphp ='yes'] $ title =newDeDeTitle(@me); $title- > bg= '#FFFFFF'; $title- > color= '#ef5c29'; $title- > width= 570; $title- > height= 35; $title- > size= 22; @ me =$title->Show(); [/field:title] </ a > {/dede:arclist}
解释一下,这里就是控制生成图片的样式的各种参数,$title->bg设置图片背景颜色,$title->color设置图片文字的颜色,$title->width这个很重要,这是设置头条图片的宽度,$title->height这个是设置头条图片的高度,$title->size这个明显就是设置头条图片的字体大小了,只要严格设置这几个不同的参数就能显示你所需求的头条图片样式,上面增加的PHP类文件里的各种参数只是个默认的参数无需修改,只要模板里修改了就不影响。
这样生成后是不是感觉头条的图片样式更加好看了。