如何使用PHP生成双色方块横竖重复排列背景的PNG图片
问题原因
现有代码每次绘制方块时都会生成随机RGB值,每个方块颜色随机,无法实现双色交替的棋盘格效果。
修改后可直接运行的代码
<?php $maxwert = 300; $size = 20; $img = imagecreatetruecolor($maxwert, $maxwert); // 定义两种方块颜色,可自行调整RGB数值修改颜色 $colorA = imagecolorallocate($img, 255, 255, 255); // 示例为白色 $colorB = imagecolorallocate($img, 0, 0, 0); // 示例为黑色 for($y=0;$y<$maxwert;$y += $size){ for($x=0;$x<$maxwert;$x+=$size){ // 按行列索引和的奇偶性切换颜色,实现交替排列 $current_color = (($x / $size) + ($y / $size)) % 2 == 0 ? $colorA : $colorB; imagefilledrectangle($img, $x, $y, $x + $size, $y + $size, $current_color); } } imagepng($img, 'imagefilledrectangle.png'); imagedestroy($img); ?>
如需调整两种颜色的具体取值,修改$colorA和$colorB对应的三个RGB参数即可。
内容的提问来源于stack exchange,提问作者Said Erraoudy
相关产品推荐
相关产品推荐

