JavaFX中有效的图像裁剪

6
我正在尝试使用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).

仅为澄清最后一行,这是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个回答

18

使用PixelReader和WritableImage应该有帮助。

以下代码可以在给定的位置(x,y)大小(width,height)处从旧图像中裁剪出新图像。

PixelReader reader = oldImage.getPixelReader();
WritableImage newImage = new WritableImage(reader, x, y, width, height);

谢谢回答,我其实已经忘记了这个问题。 - NotMyName

12

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


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