获取 JavaFX 图像的子图像以在 Canvas 上使用

the*_*Kid 2 java javafx image javafx-8

我正在用 JavaFX 搞游戏编程,我为图形制作了一个 spritesheet。目前,我正在将 JavaFX 更改Image为 a BufferedImage,然后使用该BufferedImage#subImage函数获取子图像,然后使用SwingFXUtils将其更改回 JavaFX Image。我试图寻找一种更简单的方法,但还没有找到。他们是获取 JavaFX 子映像的更简单方法吗?

Pav*_*ala 5

/*
suppose i have an image strip of 10 frames of 32x32 ( 320x32 ), then i want to separate all frames in individual images
getImage( 10, 32,32,"myStrip.png" );
*/
public static Image[] getImage( int frames, int w, int h,  String pathFile )
        {

            Image[] imgs =  new Image[ frames ];

            //img that contains all frames
            Image stripImg = new Image( pathFile );
            PixelReader pr =  stripImg.getPixelReader();
            PixelWriter pw = null;

            for( int i = 0; i < frames ; i++)
            {

                WritableImage wImg = new WritableImage( w, h );

                pw = wImg.getPixelWriter();

                for( int readY = 0 ; readY < h; readY++ )
                {

                    int ww = (w * i);
                    for( int readX = ww; readX < ww + w; readX++ )
                    {
                        //get pixel at X  & Y position
                        Color color = pr.getColor( readX, readY );

                        //set pixel to writableimage through pixel writer
                        pw.setColor(readX - ww, readY, color);

                    }//X


                }//Y


                //finally new image is stored
                imgs[ i ] = wImg;
            }//


            stripImg = null;
            pr = null;
            pw = null;

        return imgs;
        }//
Run Code Online (Sandbox Code Playgroud)