Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to set the style for line drawing using imagesetstyle() function in PHP?
The imagesetstyle() function is an inbuilt PHP function used to set custom styles for line drawing. It works with all line drawing functions like imagepolygon() and imageline() to create dashed, dotted, or patterned lines.
Syntax
bool imagesetstyle(resource $image, array $style)
Parameters
imagesetstyle() takes two parameters −
$image − The image resource to work on, created by functions like
imagecreate()orimagecreatetruecolor().$style − An array of pixel colors that defines the line pattern. Each element represents one pixel in the repeating pattern.
Return Value
Returns True on success or False on failure.
Example 1: Creating Dashed Lines
This example demonstrates creating a simple dashed line pattern ?
<?php
header("Content-type: image/jpeg");
$img = imagecreatetruecolor(700, 300);
$white = imagecolorallocate($img, 255, 255, 255);
$red = imagecolorallocate($img, 255, 0, 0);
// Fill background with white
imagefill($img, 0, 0, $white);
// Create dashed line: 5 red pixels, 5 white pixels
$style = array($red, $red, $red, $red, $red, $white, $white, $white, $white, $white);
imagesetstyle($img, $style);
imageline($img, 50, 100, 650, 100, IMG_COLOR_STYLED);
imagejpeg($img);
imagedestroy($img);
?>
Example 2: Complex Pattern with Brush
This example shows combining imagesetstyle() with imagesetbrush() for advanced patterns ?
<?php
header("Content-type: image/png");
$img = imagecreatetruecolor(400, 200);
$white = imagecolorallocate($img, 255, 255, 255);
$blue = imagecolorallocate($img, 0, 0, 255);
$green = imagecolorallocate($img, 0, 255, 0);
// Fill background
imagefill($img, 0, 0, $white);
// Create alternating blue-green pattern
$style = array($blue, $blue, $green, $green, $white, $white);
imagesetstyle($img, $style);
// Draw multiple styled lines
imageline($img, 10, 50, 390, 50, IMG_COLOR_STYLED);
imageline($img, 10, 100, 390, 100, IMG_COLOR_STYLED);
imageline($img, 10, 150, 390, 150, IMG_COLOR_STYLED);
imagepng($img);
imagedestroy($img);
?>
Key Points
The
$stylearray defines a repeating pattern for the line.Use
IMG_COLOR_STYLEDas the color parameter in drawing functions to apply the style.Combine with
IMG_COLOR_STYLEDBRUSHEDwhen using custom brushes.Transparent pixels can be used in the pattern for gaps.
Conclusion
The imagesetstyle() function provides powerful control over line appearance in PHP image manipulation. By defining custom pixel patterns, you can create professional−looking dashed, dotted, or complex styled lines for graphics and diagrams.
