通過pygame 畫座標系 、畫圖、畫線、畫點、寫字、截圖(代碼)

import os
import sys

import pygame

class Draw:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        pygame.init()
        pygame.display.set_caption('hello world')
        self.screen = pygame.display.set_mode([self.x, self.y])
        self.screen.fill([255, 255, 255])

    def drawText(self, text, posx, posy, textHeight=15, fontColor=(0, 0, 0), backgroudColor=(255, 255, 255)):
        ttf_abs = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'res', 'demo.ttf')
        fontObj = pygame.font.Font(ttf_abs, textHeight)  # 通過字體文件獲得字體對象
        textSurfaceObj = fontObj.render(text, True, fontColor, backgroudColor)  # 配置要顯示的文字
        textRectObj = textSurfaceObj.get_rect()  # 獲得要顯示的對象的rect
        textRectObj.center = (posx, posy)  # 設置顯示對象的座標
        self.screen.blit(textSurfaceObj, textRectObj)  # 繪製字

    def draw_info(self):
        color = 0, 0, 0
        width = 2
        # 畫座標系
        pygame.draw.line(self.screen, color, (0, 0), (self.x, 0), width)
        pygame.draw.line(self.screen, color, (0, 0), (0, self.y), width)
        pygame.draw.line(self.screen, color, (self.x, 0), (self.x - 10, 10), width)
        pygame.draw.line(self.screen, color, (0, self.y), (10, self.y - 10), width)
        x_list = []
        y_list = []
        self.drawText(str(0), 10, 10, textHeight=12)
        self.drawText(str(self.x), self.x - 10, 14, textHeight=12)
        self.drawText(str(self.y), 15, self.y - 10, textHeight=12)
        n = 5  # 軸分爲n段
        for i in range(1, n):
            x_list.append(int(self.x / n * i))
            y_list.append(int(self.y / n * i))
        for x_item in x_list:
            pygame.draw.line(self.screen, color, (x_item, 0), (x_item, 10), width)
            self.drawText(str(x_item), x_item, 12, textHeight=15)
        for y_item in y_list:
            pygame.draw.line(self.screen, color, (0, y_item), (10, y_item), width)
            self.drawText(str(y_item), 16, y_item, textHeight=14)
        # 加載畫圖
        pic_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'res', 'a.jpg')
        space = pygame.image.load(pic_path).convert_alpha()
        # 獲取位圖的寬和高
        width, height = space.get_size()
        # 對圖片進行縮放
        space = pygame.transform.smoothscale(space, (width // 5, height // 5))
        # 對圖片進行設置位置
        self.screen.blit(space, (100, 100))
        # 畫點(其實是畫圓)
        pygame.draw.circle(self.screen, color, (300,500), 1, 1)
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
            pygame.display.update()
            pygame.image.save(self.screen, "circle" + ".png")  # 這句話保存圖片
            pygame.quit()
            break

    def run(self):
        self.draw_info()


if __name__ == '__main__':
    x = 540
    y = 960
    Draw(x, y).draw_info()

字體庫可以複製windows自帶的.ttf文件

C:\Windows\Fonts

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章