根据字体大小缩放pygame按钮大小

问题描述 投票:0回答:1

我想采用字体大小 (14) 并使用

pygame_widgets.button.Button()
缩放它以匹配最大字体大小

我在这里看到的几乎每个问题都是相反的,目前我不熟悉将使用的数学,但我非常感谢您的帮助

import pygame
import pygame_widgets
from pygame_widgets.button import Button

pygame.init()

font_size = 14

screen = pygame.display.set_mode((640, 480))

font = pygame.font.SysFont('Arial', font_size)

Wide = 60  # Math
High = 20  # Math

button = Button(
    screen,  # surface to display
    10,  # Button's top left x coordinate
    10,  # Button's top left y coordinate
    Wide,  # Button's Width
    High,  # Button's Height
    text="Button",
    fontSize=font_size,
    inactiveColour=(255, 255, 255),
    hoverColour=(245, 245, 245),
    pressedColour=(230, 230, 230),
    radius=2,  # curve on the button corners
    onClick=lambda: print("Click")
)

while True:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        screen.fill((200, 200, 200))
        
        pygame_widgets.update(events)

        pygame.display.update()
python fonts pygame pygame-widgets
1个回答
0
投票

要根据按钮的字体大小动态缩放按钮的大小,您可以使用简单的比例缩放方法。

我已经在下面的代码中实现了它:

import pygame
import pygame_widgets
from pygame_widgets.button import Button
import sys

pygame.init()

screen = pygame.display.set_mode((640, 480))

base_font_size = 14
current_font_size = 14
max_font_size = 40  # Max font size for scaling

# Button size at base font size (14)
base_button_width = 60
base_button_height = 20

def scale_button_size(font_size, max_size):
    """ Scales the button dimensions proportionally to font size """
    scale_factor = font_size / base_font_size
    width = min(base_button_width * scale_factor, max_size)
    height = min(base_button_height * scale_factor, max_size)
    return int(width), int(height)

# Get scaled button dimensions
Wide, High = scale_button_size(current_font_size, max_font_size)

# Create button with scaled dimensions
button = Button(
    screen,
    10,  # Button's top-left x coordinate
    10,  # Button's top-left y coordinate
    Wide,  # Button's width
    High,  # Button's height
    text="Button",
    fontSize=current_font_size,
    inactiveColour=(255, 255, 255),
    hoverColour=(245, 245, 245),
    pressedColour=(230, 230, 230),
    radius=2,
    onClick=lambda: print("Click")
)

while True:
    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    screen.fill((200, 200, 200))
    pygame_widgets.update(events)
    pygame.display.update()
© www.soinside.com 2019 - 2024. All rights reserved.