Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Libgdx crop image to circle

Tags:

crop

libgdx

I'm looking for a way to crop a photo taken from the users gallery to a circle, to be displayed as a profile picture basically.

I've been recommended to use Masking . But I can't work out how to actually do it. There are virtually no examples of it, except with android code. But since I'm going to port my game to IOS as well I need a Libgdx solution.

So has anyone done this before and have an working example perhaps?

Here's how I'll fetch the image:

ublic void invokeGallery() {
    if (utils != null) {
        loading = true;
        utils.pickImage(new utilsInterface.Callback() {
            @Override
            public ImageHandler onImagePicked(final InputStream stream) {
                loading = true;
                final byte[] data;
                try {
                    data = StreamUtils.copyStreamToByteArray(stream);

                    Gdx.app.postRunnable(new Runnable() {
                        @Override
                        public void run() {


                            loading = false;
                        }
                    });


                } catch (IOException e) {
                    e.printStackTrace();
                }
                loading = false;
                return null;
            }
        });
    }
}
like image 288
Benni Avatar asked Jan 25 '16 15:01

Benni


1 Answers

I use this, it works, but there is no interpolation, which means the edges are pixelated. You can chose to either implement interpolation or use a border!

public static Pixmap roundPixmap(Pixmap pixmap)
{
    int width = pixmap.getWidth();
    int height = pixmap.getHeight();
    Pixmap round = new Pixmap(pixmap.getWidth(),pixmap.getHeight(),Pixmap.Format.RGBA8888);
    if(width != height)
    {
        Gdx.app.log("error", "Cannot create round image if width != height");
        round.dispose();
        return pixmap;
    }
    double radius = width/2.0;
    for(int y=0;y<height;y++)
    {
        for(int x=0;x<width;x++)
        {
            //check if pixel is outside circle. Set pixel to transparant;
            double dist_x = (radius - x);
            double dist_y = radius - y;
            double dist = Math.sqrt((dist_x*dist_x) + (dist_y*dist_y));
            if(dist < radius)
            {
                round.drawPixel(x, y,pixmap.getPixel(x, y));
            }
            else
                round.drawPixel(x, y, 0);
        }
    }
    Gdx.app.log("info", "pixmal rounded!");
    return round;
}

Do keep in mind this will all be unmanaged! To make life easier I usually save the image and load it as a managed texture.

like image 168
p.streef Avatar answered Nov 03 '22 02:11

p.streef