libgdximage-rotationpixmap

How to draw rotated image on pixmap (LibGDX)


How can I draw an image to Pixmap, but rotated by some angle, like I can do when drawing on Batch? There is no Pixmap method that has an angle as parameter, like batch drawing methods have.


Solution

  • Ok, here is the code I managed to make (actually to borrow and adjust from here: Rotate Bitmap pixels ):

    public Pixmap rotatePixmap (Pixmap src, float angle){
        final int width = src.getWidth();
        final int height = src.getHeight();
        Pixmap rotated = new Pixmap(width, height, src.getFormat());
    
        final double radians = Math.toRadians(angle), cos = Math.cos(radians), sin = Math.sin(radians);     
    
    
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                final int
                centerx = width/2, centery = height / 2,
                m = x - centerx,
                n = y - centery,
                j = ((int) (m * cos + n * sin)) + centerx,
                k = ((int) (n * cos - m * sin)) + centery;
                if (j >= 0 && j < width && k >= 0 && k < height){
                    rotated.drawPixel(x, y, src.getPixel(j, k));
                }
            }
        }
        return rotated;
    
    }
    

    It creates and returns rotated Pixmap out of passed source Pixmap. It rotates around the center and it's actually pretty fast, on PC and on my HTC Sensation.

    And don't forget to dispose Pixmap you get after the usage.

    It would be nice to have system solution for this which would be more optimized, have rotation point coordinates, but this does the job for me, hopefully will be helpful for somebody else.