mask method

void mask({
  1. PImage? maskImage,
  2. List<int>? maskPixels,
})

Masks this PImage with the given maskImage or the given maskPixels.

maskImage or maskPixels must be provided, but not both.

If a maskImage is provided, the alpha channel in this PImage is set equal to the blue channel of the pixels in the maskImage. A maskImage pixel with a blue value of 255 will fully reveal the pixel within this PImage. A pixel with a blue value of 0 will fully erase the pixel within this PImage.

If maskPixels is provided, the pixel alpha values in this PImage are set equal to the given maskPixels values.

Implementation

void mask({
  PImage? maskImage,
  List<int>? maskPixels,
}) {
  if (maskImage == null && maskPixels == null) {
    throw Exception("PImage#mask() requires either a maskImage or maskPixels");
  }
  if (maskImage != null && maskPixels != null) {
    throw Exception("PImage#mask() should be given a maskImage or maskPixels, but not both");
  }
  if (maskImage != null) {
    if (maskImage.width != width || maskImage.height != height) {
      throw Exception(
          "PImage#mask() must use a maskImage (${maskImage.width}, ${maskImage.height}) with the same dimensions as the base image: ($width, $height)");
    }
  }
  if (maskPixels != null) {
    if (maskPixels.length != width * height) {
      throw Exception(
          "PImage#mask() must receive a maskPixels (${maskPixels.length}) with the same number of pixels as the base image (${width * height})");
    }
  }

  if (maskImage != null) {
    for (int x = 0; x < width; x += 1) {
      for (int y = 0; y < height; y += 1) {
        final existingColor = get(x, y);
        final maskAlpha = maskImage.get(x, y).blue;
        final newColor = maskAlpha == 0 ? const Color(0x00000000) : existingColor.withAlpha(maskAlpha);
        set(x, y, newColor);
      }
    }
  } else {
    for (int x = 0; x < width; x += 1) {
      for (int y = 0; y < height; y += 1) {
        final existingColor = get(x, y);
        final maskAlpha = maskPixels![_getBitmapPixelOffset(imageWidth: width, x: x, y: y)];
        final newColor = maskAlpha == 0 ? const Color(0x00000000) : existingColor.withAlpha(maskAlpha);
        set(x, y, newColor);
      }
    }
  }

  _isFlutterImageDirty = true;
}