如何在libgdx中翻转pixmap以绘制到纹理上?

12

我的目标是通过将像素图绘制到纹理中生成游戏的背景图像。目前我已经能够做到这一点,但现在我需要将像素图翻转到纹理中的X或Y轴上。然而,我无法找到任何可以实现这样操作的方法。像素图类不提供该功能。然后我想到,我可以将翻转的纹理区域绘制到纹理中,但到目前为止我还没有找到如何实现这一点的方法。因此,我想知道如何才能做到这一点,是否可能使用其他Java库来翻转PNG图像,然后从翻转后的图像创建一个像素图?

2个回答

9
我也没有其他选择,除了迭代像素:
public Pixmap flipPixmap(Pixmap src) {
    final int width = src.getWidth();
    final int height = src.getHeight();
    Pixmap flipped = new Pixmap(width, height, src.getFormat());

    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            flipped.drawPixel(x, y, src.getPixel(width - x - 1, y));
        }
    }
    return flipped;
}

记得释放原始的Pixmap - Will Kru
2
谢谢!顺便说一下,如果你想在Y轴上翻转,只需执行 flipped.drawPixel(x, y, src.getPixel(x, height - y - 1)); - Sawny
如果您需要将像素图旋转90度:我创建了一个方法来实现这个想法,详情请见http://stackoverflow.com/a/34362685/2399024。 - donfuxx

1
这是一种不需要创建新 Pixmap 的解决方案。此代码还可以通过交换 pixmap 图像的角而不是交换图像相对面上的像素来水平和垂直翻转 Pixmap。
public static void flipPixmap( Pixmap p ){
    int w = p.getWidth();
    int h = p.getHeight();
    int hold;

    //change blending to 'none' so that alpha areas will not show
      //previous orientation of image
    p.setBlending(Pixmap.Blending.None);
    for (int y = 0; y < h / 2; y++) {
        for (int x = 0; x < w / 2; x++) {
            //get color of current pixel
            hold = p.getPixel(x,y);
            //draw color of pixel from opposite side of pixmap to current position
            p.drawPixel(x,y, p.getPixel(w-x-1, y));
            //draw saved color to other side of pixmap
            p.drawPixel(w-x-1,y, hold);
            //repeat for height/width inverted pixels
            hold = p.getPixel(x, h-y-1);
            p.drawPixel(x,h-y-1, p.getPixel(w-x-1,h-y-1));
            p.drawPixel(w-x-1,h-y-1, hold);
        }
    }
    //set blending back to default
    p.setBlending(Pixmap.Blending.SourceOver);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接