Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

libGDX: How can I crop Texture as a circle

I achieved my goal with android development as shown in this link Cropping circular area from bitmap in Android but how can I achieve that with libGDX framework? I tried to do it with Pixmap but not succeeded with me.

Anyone can Help me to achieve that.

like image 588
iibrahimbakr Avatar asked Mar 13 '23 21:03

iibrahimbakr


1 Answers

I don't know if there's an easier way, but I made a method for working with masks and combining the mask with the original pixmap into a resulting pixmap.

public void pixmapMask(Pixmap pixmap, Pixmap mask, Pixmap result, boolean invertMaskAlpha){
    int pixmapWidth = pixmap.getWidth();
    int pixmapHeight = pixmap.getHeight();
    Color pixelColor = new Color();
    Color maskPixelColor = new Color();

    Pixmap.Blending blending = Pixmap.getBlending();
    Pixmap.setBlending(Blending.None);
    for (int x=0; x<pixmapWidth; x++){
        for (int y=0; y<pixmapHeight; y++){
            Color.rgba8888ToColor(pixelColor, pixmap.getPixel(x, y));                           // get pixel color
            Color.rgba8888ToColor(maskPixelColor, mask.getPixel(x, y));                         // get mask color

            maskPixelColor.a = (invertMaskAlpha) ? 1.0f-maskPixelColor.a : maskPixelColor.a;    // IF invert mask
            pixelColor.a = pixelColor.a * maskPixelColor.a;                                     // multiply pixel alpha * mask alpha
            result.setColor(pixelColor);
            result.drawPixel(x, y);
        }
    }
    Pixmap.setBlending(blending);
}

The only thing looked at on the mask pixmap is the alpha channel. It samples the alpha from the mask and combines that with the alpha from the original pixamp, then it writes the value to the result pixmap.

In your case, draw a filled circle onto the mask pixmap with any color as long as the alpha is "1f". Then the result pixmap will be your original pixmap cropped to a circle.

NOTE: The "invertMaskAlpha" boolean allows you to flip the mask's alpha channel. So if you set this boolean to "true" you will have your original pixmap with the circle cut out of it leaving only the edges outside the circle.

like image 96
Tekkerue Avatar answered Mar 25 '23 08:03

Tekkerue