卡卷网
当前位置:卡卷网 / 每日看点 / 正文

pygame怎么输出汉字?为啥我写的这个显示出来是方框?

作者:卡卷网发布时间:2025-01-18 19:14浏览数量:81次评论数量:0次

1,将图像或文本绘制到屏幕上 screen.blit()

问题:pygame默认显示中文乱码怎么办?如何显示不同字体?

解决方法:下载想用的字体到本地, .ttf文件,本地引用

pygame怎么输出汉字?为啥我写的这个显示出来是方框?  第1张


2,代码

""" 1,添加方法,获取rgb颜色的值,把rgb颜色对照表的数据封装成方法,直接导包使用 2,显示文字/绘制不同字体的中文 """ import pygame import sys import RgbColors as Rgb pygame.init() # 设置默认窗口大小 screen_width = 1000 screen_height = 600 # 创建Surface(显示)对象 screen = pygame.display.set_mode((screen_width, screen_height), pygame.RESIZABLE) # 设置窗口标题 pygame.display.set_caption("我的第一个 Pygame 游戏") # 加载图标图像 icon = pygame.image.load(r'D:\pythonworkspace\game\icon\icon.png') # 设置窗口的图标 pygame.display.set_icon(icon) # # 创建字体对象 # font = pygame.font.Font(None, 36) # None 表示使用默认字体,36 是字体大小 # 加载支持中文的字体文件 font_path = r"D:\pythonworkspace\game\font\AlimamaFangYuanTiVF-Thin-2.ttf" # 替换为你的字体文件路径 font = pygame.font.Font(font_path, 40) # 设置字体大小 # 加载图像 image = pygame.image.load(r"D:\pythonworkspace\game\icon\SEED_2539913529.png") # 替换为你的图片路径 # 获取图像的矩形区域 image_rect = image.get_rect(center=(700, 300)) # 设置图像的中心位置 # 设置颜色 def get_rgb_tuple(color_dict): """ 从包含 'RGB' 键的字典中获取 RGB 值,并将其转换为整数元组。 :param color_dict: 包含 'RGB' 键的字典 :return: RGB 值的整数元组 """ # 将字符串按逗号分割,并转换为整数元组 rgb_tuple = tuple(map(int, color_dict['RGB'].split(','))) return rgb_tuple # 获取颜色 Azure = get_rgb_tuple(Rgb.Azure) Yellow = get_rgb_tuple(Rgb.Yellow) Red = get_rgb_tuple(Rgb.Red) SteelBlue1 = get_rgb_tuple(Rgb.SteelBlue1) Black = get_rgb_tuple(Rgb.Black) White = get_rgb_tuple(Rgb.White) # 事件循环 running = True while running: # 获取事件队列中的所有事件 for event in pygame.event.get(): # 如果事件类型是退出事件,则退出循环 if event.type == pygame.QUIT: running = False # 填充屏幕 screen = pygame.display.get_surface() screen.fill(SteelBlue1) # 渲染中文 text = "hello! 交个朋友吗?" text_surface = font.render(text, True, Black, White) # 获取文字矩形对象 text_rect = text_surface.get_rect(center=(200, 300)) # 绘制文字 screen.blit(text_surface, text_rect) # 绘制图像 screen.blit(image, image_rect) # 更新屏幕 pygame.display.flip() # 退出 Pygame pygame.quit() sys.exit()


运行后:

pygame怎么输出汉字?为啥我写的这个显示出来是方框?  第2张


3,笔记:

将图像或文本绘制到屏幕上 screen.blit(source, dest, area=None, special_flags=0)

参数:

  • source:要绘制的 Surface 对象(例如文本、图像等)。
  • dest:目标位置,可以是一个 (x, y) 坐标元组,或者一个 Rect 对象。
  • area(可选):指定从 source 中复制的区域(一个 Rect 对象)。如果为 None,则复制整个 Surface。
  • special_flags(可选):特殊绘制标志(如混合模式),通常不需要使用。
END

免责声明:本文由卡卷网编辑并发布,但不代表本站的观点和立场,只提供分享给大家。

卡卷网

卡卷网 主页 联系他吧

请记住:卡卷网 Www.Kajuan.Net

欢迎 发表评论:

请填写验证码