How to draw rotated image on pixmap (LibGDX)

喜欢而已 提交于 2019-12-24 07:06:29

问题


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.


回答1:


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.




回答2:


Your code has the k and j reversed. As-is, an angle of 0 degrees should draw the same thing, but it doesn't. It rotates it 90 degrees. So the one line should be

rotated.drawPixel(x, y, src.getPixel(j, k));

instead of

rotated.drawPixel(x, y, src.getPixel(k, j));

Otherwise, works like a champ.



来源:https://stackoverflow.com/questions/22441928/how-to-draw-rotated-image-on-pixmap-libgdx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!