【问题标题】:Scale image for ImageButton and then center it缩放 ImageButton 的图像,然后将其居中
【发布时间】:2015-03-30 10:16:12
【问题描述】:

我想做什么:

    final ImageButtonStyle upStyle = new ImageButtonStyle();
    upStyle.up = spriteUp;
    upStyle.down = spriteDown;
    upStyle.imageUp = spriteIcon;

    imgButton = new ImageButton(upStyle);
    imgButton.getImage().setScale(0.5f);

但是,这会产生以下结果:

这就是我想要的:

为了立即实现这一点,我必须调用以下代码:

float scale = 0.5f;
imgButton.pack();
imgButton.getImage().setOrigin(imgButton.getImage().getWidth() * scale, imgButton.getImage().getHeight() * scale);

我尝试过但没有结果的事情(没有特定的顺序):

imgButton.getImage().setAlign(Align.center);
imgButton.invalidate();
imgButton.pack();
imgButton.getImageCell().align(Align.center);

任何想法,也许是一些与单元格属性有关的想法?除非我手动更改 Origin 并重新打包,否则似乎没有任何改变...

谢谢!

【问题讨论】:

    标签: java libgdx scene2d


    【解决方案1】:

    试试

    imgButton.getImage().setOrigin(Align.center);
    imgButton.getImage().setScale(0.5f);
    

    LibGDX 没有使用宽度宽度和高度 * 0.5f 的技巧并将其用作原点,而是使用 Align.center 指定中心的好方法。

    【讨论】:

      【解决方案2】:

      这就是最终奏效的方法:

          final ImageButtonStyle upStyle = new ImageButtonStyle();
          upStyle.up = spriteUp;
          upStyle.down = spriteDown;
          upStyle.imageUp = spriteIcon;
          imgButton = new ImageButton(upStyle);
      
          final float scale = 0.5f;
          imgButton.getImage().setScale(scale);
      
          // Calling any of these works.
          imgButton.pack();
          imgButton.layout();
          imgButton.validate();
      
          // Calling these doesn't work.
          imgButton.invalidate();
          imgButton.invalidateHierarchy();
      
          // Has to be called after either pack(), layout(), or validate() are called.
          imgButton.getImage().setOrigin(Align.center);
      
          stage = new Stage(new StretchViewport(500, 700));
          stage.addActor(imgButton);
      

      我不明白为什么在设置比例后我必须调用 pack()、layout() 或 validate() 中的任何一个……但在尝试了许多组合之后,我发现它可以工作。也许有人可以更深入地了解为什么会这样工作,也许有更好的方法?

      理想情况下我想做的是这样的:

      final float scale = 0.5f;
      imgButton.getImage().setScale(scale);
      imgButton.getImage().setOrigin(Align.center);
      
      // or
      final float scale = 0.5f;
      imgButton.getImage().setScale(scale);
      imgButton.getImage().setOrigin(Align.center);
      imgButton.pack();   // Forcing a pack / invalidate I can live with.
      

      【讨论】:

      • 同样考虑到图像被添加到按钮的表格中,图像的定位/放置不应该由单元格属性控制吗?我试过用细胞做,但没有成功。我希望这样:“imgButton.getImageCell().align(Align.center);”以这种方式行事。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 2011-09-30
      • 2011-01-02
      相关资源
      最近更新 更多