From 2ffdd4e1553381c88516cbab0355d7c53dd8d532 Mon Sep 17 00:00:00 2001 From: TheSwampire Date: Thu, 30 Sep 2021 19:37:23 +0200 Subject: [PATCH] Dynamic background image resizing, preserving aspect ratio --- .../launcher/FancyBackgroundPanel.java | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/launcher-fancy/src/main/java/com/skcraft/launcher/FancyBackgroundPanel.java b/launcher-fancy/src/main/java/com/skcraft/launcher/FancyBackgroundPanel.java index 19ee6fa..73f747f 100644 --- a/launcher-fancy/src/main/java/com/skcraft/launcher/FancyBackgroundPanel.java +++ b/launcher-fancy/src/main/java/com/skcraft/launcher/FancyBackgroundPanel.java @@ -27,8 +27,35 @@ public class FancyBackgroundPanel extends JPanel { protected void paintComponent(Graphics g) { super.paintComponent(g); if (background != null) { - g.drawImage(background, 0, 0, null); + double multi; + int w, h; + + // Calculate Aspect Ratio Multiplier depending on window size + if (this.getHeight() <= this.getWidth()) { + multi = this.getWidth() / (float)background.getWidth(null); + } + else { + multi = this.getHeight() / (float)background.getHeight(null); + } + + // Calculate new width and height + w = (int) Math.floor((float)background.getWidth(null) * multi); + h = (int) Math.floor((float)background.getHeight(null) * multi); + + // Check if it needs to be switched (eg. in case of a square window) + if (h < this.getHeight() || w < this.getWidth()) { + if (h < this.getHeight()) { + multi = this.getHeight() / (float)background.getHeight(null); + } + else if (w < this.getWidth()) { + multi = this.getWidth() / (float) background.getWidth(null); + } + + w = (int) Math.floor((float)background.getWidth(null) * multi); + h = (int) Math.floor((float)background.getHeight(null) * multi); + } + + g.drawImage(background, 0, 0, w, h,null); } } - }