JavaFX中的有效图像裁剪

时间:2013-02-10 20:43:02

标签: image javafx

我正在尝试使用JavaFX编写拼图游戏,部分原因是有人问我,部分是因为我想给JavaFX一个机会。但是,我对图像的实际裁剪有困难。

这个想法是让用户提供图像和程序将图像切割成更小的部分。简单吧?我的问题是:我能找到切割图像的唯一方法是制作图像对象的副本并更改副本的可见部分,这是一个例子:

ImageView imgageView = new ImageView(); // Creates a new ImageView; this will be a single puzzle piece.
imgageView.setImage(originalImage); // Use the original image as the "base."
Rectangle2D rectangle = new Rectangle2D(0, 0, 50, 50); // Crop the image from (0,0) to (50, 50).

只是澄清最后一行,这是related piece in the API

public Rectangle2D(double minX,
           double minY,
           double width,
           double height)
Creates a new instance of Rectangle2D.
Parameters:
minX - The x coordinate of the upper-left corner of the Rectangle2D
minY - The y coordinate of the upper-left corner of the Rectangle2D
width - The width of the Rectangle2D
height - The height of the Rectangle2D

现在这很好,如果我将图片切成四到九块(游戏是针对幼儿的),但是如果我想将图片切成一块漂亮的1200块拼图呢?这不会导致极其昂贵的操作吗?不仅要裁剪本身,还要将图像的许多副本保留在内存中。看,如果我正确理解这一点,每件作品都将包含整个原始图像,其中大部分将保持“隐藏”。

我只是误解了这个功能?如果没有,那么必须有更好的方法来做到这一点,对吗?

2 个答案:

答案 0 :(得分:14)

使用PixelReader和WritableImage应该会有所帮助。

以下内容会从position (x,y)size (width, height)

中删除旧图片
PixelReader reader = oldImage.getPixelReader();
WritableImage newImage = new WritableImage(reader, x, y, width, height);

答案 1 :(得分:9)

多个ImageView对象可以引用相同的Image。图像本身的数据存储在图像中。如果你有1000个ImageView对象,每个对象引用相同的Image,那么内存中只有1个像素副本。使用WriteableImage创建副本实际上比拥有多个ImageView对象更昂贵。