【问题标题】:Setting ImageViews as button background failing将 ImageViews 设置为按钮背景失败
【发布时间】:2020-05-13 17:56:35
【问题描述】:

上下文:我正在创建一个益智游戏作为项目的一部分,我已经完成了逻辑并且只想为我的按钮设置背景。

我在这里找到的用于创建 BackgroundImages 的代码,当它设置背景时,每个按钮都会接收 ImageView 列表中的第一个元素。

这是显示 ImageView 列表中每个按钮接收元素 0 的结果,下面我显示了所有 4 个元素,只是为了检查我正确填充了 ImageView 列表。

List<Button> pieces = new ArrayList<>();
List<ImageView> images = new ArrayList<>();
VBox layout = new VBox();
HBox original = new HBox();
Image image = new Image("jalter.png");  
HBox imagesList = new HBox();   



for(int i = 0; i < 4; i++) { 
  pieces.add(new Button(String.valueOf(i+1)));
  pieces.get(i).setPrefSize(150,150);  

  images.add(new ImageView(image));  
  images.get(i).setViewport(new Rectangle2D(
  getX(toGridXY(i)) * 150,
  getY(toGridXY(i)) * 150,
  150,
  150));    

  BackgroundImage backgroundImage = new                     
  BackgroundImage
  (images.get(i).getImage(), 
  BackgroundRepeat.NO_REPEAT, 
  BackgroundRepeat.NO_REPEAT, 
  BackgroundPosition.DEFAULT, 
  BackgroundSize.DEFAULT);  
  Background background = new 
  Background(backgroundImage);      
  pieces.get(i).setBackground(background);      
}

【问题讨论】:

    标签: java button javafx arraylist imageview


    【解决方案1】:

    您将每个人的背景设置为具有完全相同图像的背景。 ImageView.getImage() 只是要返回你传递的原始图像;它不会将该图像裁剪到图像视图的视口。

    相反,您可以使用原始图像的pixelReader 创建一个新的Image,并在WritableImage 的构造函数中提供裁剪区域:

    for(int i = 0; i < 4; i++) { 
      Button button = new Button(String.valueOf(i+1));
      pieces.add(button);
      button.setPrefSize(150,150);  
    
      Image croppedImage = new WritableImage(image.getPixelReader(),
        getX(toGridXY(i)) * 150,
        getY(toGridXY(i)) * 150,
        150,
        150);
    
      BackgroundImage backgroundImage = new BackgroundImage(
        croppedImage,
        BackgroundRepeat.NO_REPEAT, 
        BackgroundRepeat.NO_REPEAT, 
        BackgroundPosition.DEFAULT, 
        BackgroundSize.DEFAULT);  
      Background background = new Background(backgroundImage);      
      button.setBackground(background);      
    }
    

    【讨论】:

    • 谢谢詹姆斯,我不明白 getImage() 在做什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 2014-06-20
    • 1970-01-01
    相关资源
    最近更新 更多