簡體   English   中英

在pyglet中繪制沒有空格的PNG

[英]Draw PNG without whitespace in pyglet

我編寫了一個程序來渲染我在一個名為 tiled 的程序中制作的地圖。 地圖有多個圖層,程序可以 output 到.json 所以我寫了一個程序來解釋.json 文件並顯示 Z90178DC81ED51244E Z90178DC8ED51244. 然而,在我讓程序運行后,我意識到當我在第二層上繪制灌木叢時,由於 png 上的空白區域,它會刪除后面層中的所有內容。 有沒有辦法在沒有空格的pyglet中繪制PNG?

帶空格: https://imgur.com/VlnXUP2

平鋪(沒有虛線的預期外觀): https://imgur.com/xbw1K4K

import pyglet
import pyglet.gl as gl
import json

# read json file and specifically get the "data","height","width"
f = open("TILED-FILES/16x16 map2.json","r")
map = json.load(f)
layers = map['layers']

screen = pyglet.window.Window(resizable=True)

background = pyglet.image.load('/Users/naghs/srcHome/game/images/grass.png')
background.anchor_x = background.width // 2
background.anchor_y = background.height // 2

def center_image(img):
    img.anchor_x = img.width // 2
    img.anchor_y = img.height // 2

def formatMap(alist,width,height):
    matrix = []
    j1 = []
    for j in range(height):
        j1 = []
        for i in range(width):
            j1.append(alist[i*j])
            pass
        matrix.append(j1)
    return matrix

def drawTile(x,y,i=int,scale = 2):
    if i == 0:
        return
    tile = pyglet.image.load(f'tiny 16 basic tilesets/basictiles/basictiles{i}.png')
    width = 16 * scale
    height = 16 * scale
    texture = tile.get_texture()   
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)                                                                                                                               
    texture.width = width # resize from 8x8 to 16x16                                                                                                                                                                  
    texture.height = height
    texture.blit(x,y)
    center_image(tile)
    texture.blit(x,y)
    pass

def draw_layer(layer,scale=2):
    map = layer["data"]
    height = layer['height']
    width = layer['width']
    tile = 16 * scale
    map = formatMap(map,width,height)
    print(map)
    y = 0
    for y1 in range(0,height*tile,tile):
        x = 0
        for x1 in range(0,width*tile,tile):
            print(map[y][x])
            drawTile(x1,y1,i=map[y][x],scale=scale)
            x += 1
        y += 1
        
# Old
def draw_background():
    tile = background.width
    for x in range(0,screen.width+tile,tile):
        for y in range(0,screen.height+tile,tile):
            background.blit(x,y)

@screen.event
def on_draw():
    screen.clear()
    draw_layer(layers[0])
    draw_layer(layers[1])


pyglet.app.run()

確保您的.PNG 實際上是透明的。 您尚未提供要加載的文件,因此我無法驗證。

如果不是,最簡單的方法是在 Gimp 之類的程序中刪除背景並加載具有透明背景的文件。

順便說一句:根據我的測試pyglet.resource.image()pyglet.image.load()快,並確保使用f.close()關閉 json 文件或使用

with open("TILED-FILES/16x16 map2.json", "r") as file:
    map = json.load(file)

一旦你退出它就會with你關閉它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM