2013-02-10 50 views
5

我试图用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块拼图?这不会导致一个非常昂贵的操作?不仅裁剪本身,而且要在内存中保留很多图像副本。看看,如果我正确地理解了这一点,那么每件作品都将包含整个原始图像,其中大部分将保持“隐藏”。

我只是误解了函数?如果没有,那么一定有更好的方法来做到这一点,对吧?

回答

11

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

以下切断从旧一个新的图像在position (x,y)size (width, height)

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

感谢您的回答,我实际上已经忘记了这个问题。 – NotMyName 2013-03-26 14:02:49

9

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