You are here

public function PositionedRectangle::addGrid in Image Effects 8.3

Same name and namespace in other branches
  1. 8 src/Component/PositionedRectangle.php \Drupal\image_effects\Component\PositionedRectangle::addGrid()
  2. 8.2 src/Component/PositionedRectangle.php \Drupal\image_effects\Component\PositionedRectangle::addGrid()

Add points representing a grid within the rectangle.

The grid point coordinates need to be integers, since we are handling pixels here. In case the grid cells dimensions do not fit with integers, the remainder pixels are distributed evenly around the midpoint of the grid.

Parameters

string $id: An identifier of the grid.

int $x: The x-coordinate of the top-left point of the grid.

int $y: The y-coordinate of the top-left point of the grid.

int $width: The width of the grid.

int $height: The height of the grid.

int $rows: The number of rows of the grid.

int $columns: The number of columns of the grid.

Return value

$this

File

src/Component/PositionedRectangle.php, line 152

Class

PositionedRectangle
Rectangle algebra class.

Namespace

Drupal\image_effects\Component

Code

public function addGrid($id, $x, $y, $width, $height, $rows, $columns) {
  $cell_width = (int) ($width / $columns);
  $width_remainder = $width - $cell_width * $columns;
  $width_midpoint = (int) $columns / 2 - (int) $width_remainder / 2;
  $cell_height = (int) ($height / $rows);
  $height_remainder = $height - $cell_height * $rows;
  $height_midpoint = (int) $rows / 2 - (int) $height_remainder / 2;
  $x_offset = $x;
  $w_remainder = $width_remainder;
  for ($i = 0; $i <= $columns; $i++) {
    if ($i >= $width_midpoint && $w_remainder > 0) {
      $x_offset++;
      $w_remainder--;
    }
    $y_offset = $y;
    $h_remainder = $height_remainder;
    for ($j = 0; $j <= $rows; $j++) {
      if ($j >= $height_midpoint && $h_remainder > 0) {
        $y_offset++;
        $h_remainder--;
      }
      $this
        ->setPoint($id . '_' . $j . '_' . $i, [
        $x_offset,
        $y_offset,
      ]);
      $y_offset += $cell_height;
    }
    $x_offset += $cell_width;
  }
  return $this;
}