copy method

PImage copy([
  1. Rect? rect
])

Copies and returns all, or part of, this PImage.

Implementation

PImage copy([Rect? rect]) {
  final copyRect = rect ?? Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble());
  if (copyRect.left < 0 || copyRect.top < 0 || copyRect.right > width || copyRect.bottom > height) {
    throw Exception("Invalid copy region passed to PImage#copy. Image size: ${width}x$height, rect: $copyRect");
  }

  final newImage = PImage.empty(copyRect.width.round(), copyRect.height.round(), ImageFileFormat.png);
  final colStart = copyRect.left.round();
  final colEnd = copyRect.right.round();
  final rowStart = copyRect.top.round();
  final rowEnd = copyRect.bottom.round();

  for (int col = colStart; col < colEnd; col += 1) {
    for (int row = rowStart; row < rowEnd; row += 1) {
      newImage.set(col - colStart, row - rowStart, get(col, row));
    }
  }

  return newImage;
}