Search code examples
androiddynamicbitmapmask

Android dynamic bitmap mask


I have this image:

enter image description here

I also have an α value whose range is [0, π]. Essentialy, it represents the visible angle.

I want to apply a dynamic transparent mask to the image, so if α equals π/2, only the left half is visible.

I've thought of this process to calculate each pixel visibility:

private boolean[][] getVisibilityArray(final int height, final int width, final double value) {

    final boolean[][] visibility = new boolean[width][height];
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            final double xInSqrt = (width / 2) - x;
            final double yInSqrt = height - y;
            final double sumInSqrt = xInSqrt * xInSqrt + yInSqrt * yInSqrt;
            final double hipotenusa = Math.sqrt(sumInSqrt);
            final double adyacente = Math.abs((width / 2) - x);
            final double cos = adyacente / hipotenusa;
            double angle = Math.acos(cos);
            if (x > width / 2) {
                angle = Math.PI - angle;
            }
            visibility[x][y] = angle <= value;
        }
    }
    return visibility;
}

However, generating the bitmap and applying the mask to my original bitmap is beyond my understanding.

How can I achieve this effect?


Solution

  • In the end, the answer was more obvious than I initially thought.

    final boolean[][] visibility = getVisibilityArray(currentGauge.getHeight(),
                        currentGauge.getWidth(), angle);
    final Bitmap clone = Bitmap.createBitmap(currentGauge.getWidth(),
                        currentGauge.getHeight(), Config.ARGB_8888);
    for (int y = 0; y < currentGauge.getHeight(); y++) {
        for (int x = 0; x < currentGauge.getWidth(); x++) {
            if (!visibility[x][y]) {
                clone.setPixel(x, y, 0);
            } else {
                clone.setPixel(x, y, currentGauge.getPixel(x, y));
            }
        }
    }
    

    Clone contains the desired bitmap. No masking, just setting the unwanted pixels to 0 (0x00000000 is 0% opacity black) so they become transparent.