【问题标题】:Draw an image with a relative size to Panel绘制与 Panel 相对大小的图像
【发布时间】:2016-10-08 11:30:52
【问题描述】:

我知道如何使用 java 绘制图像(使用 paintComponent 方法),但我有一个问题: 当我调整框架大小时,图像保持相同大小,但我希望它在我增加框架大小时增加它的大小,并在我减小框架大小时减小它的大小。

我的代码:

@Override
public void paintComponent(Graphics graphics) {
    Graphics2D g = (Graphics2D) graphics;
    g.drawImage(myImage, x, y, myWidth, myHeight, null);

}

我确定我需要使用 JPanel 类的 getWidth 和 getHeight 方法,但我不知道我需要做的数学运算。

【问题讨论】:

  • 您需要选择图像的相对大小(例如帧宽度的 80%),然后选择scale it
  • 覆盖 JPanel 的 getPreferredSize,这里有很多例子和 SSCCE /MCVE 形式
  • I'm sure that I need to use the getWidth and getHeight method of the JPanel class - 正确,就这样做。只需更改您的代码以使用这些方法。此外,您应该使用“this”而不是“null”作为 drawImage(...) 方法的最后一个参数。
  • 好的,谢谢大家,我稍后试试

标签: java swing graphics position 2d


【解决方案1】:

除了在paintComponents 中编写此代码之外,您还可以放入一个JFrame 的重写paint 方法。

这样,当您调整窗口大小时,会调用paint方法并调整图像大小。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多