getRegion method

Future<PImage> getRegion({
  1. required int x,
  2. required int y,
  3. required int width,
  4. required int height,
})

Creates a returns a new PImage that replicates a region of this PImage, defined by the given (x,y) origin and the given width and height.

Implementation

Future<PImage> getRegion({
  required int x,
  required int y,
  required int width,
  required int height,
}) async {
  final destinationData = Uint8List(width * height * 4);
  final rowLength = width * 4;

  for (int row = 0; row < height; row += 1) {
    final sourceRowOffset = _getBitmapPixelOffset(
      imageWidth: width,
      x: x,
      y: y + row,
    );
    final destinationRowOffset = _getBitmapPixelOffset(
      imageWidth: width,
      x: 0,
      y: row,
    );

    destinationData.setRange(
      destinationRowOffset,
      destinationRowOffset + rowLength - 1,
      Uint8List.view(pixels.buffer, sourceRowOffset, rowLength),
    );
  }

  return PImage.fromPixels(width, height, ByteData.view(destinationData.buffer), format);
}