Python使用svgwrite生成SVG时如何消除相邻矩形之间的缝隙
问题描述
使用Python的svgwrite库生成SVG格式图表,目标是根据由0和1组成的数组渲染对应黑白方块:0对应黑色方块,1对应白色方块。实现代码如下:
import numpy as np import svgwrite CSS_STYLES = """ .background { fill: white; } .blacksquare { fill: black; } .whitesquare { fill: white; } """ def draw_board(dwg, data, block_sz): def group(classname): return dwg.add(dwg.g(class_=classname)) # setup element groups white_squares = group("whitesquare") black_squares = group("blacksquare") board_height = data.shape[0] board_width = data.shape[1] # draw squares for x in range(board_width): for y in range(board_height): xc = x * block_sz yc = y * block_sz square = dwg.rect(insert=(xc, yc), size=(block_sz, block_sz)) (white_squares if data[y][x] == 1 else black_squares).add(square) def main(): data = np.array([[0, 1, 1, 0, 0], [1, 0, 1, 0, 0]]) # data represents an array of 0 and 1s. 0 means black square and 1 means white square block_sz = 10 # units per square num_y_blocks = data.shape[0] num_x_blocks = data.shape[1] BOARD_WIDTH = "{}cm".format(num_x_blocks * block_sz) # size of the PCB board BOARD_HEIGHT = "{}cm".format(num_y_blocks * block_sz) # size of the PCB board BOARD_SIZE = (BOARD_WIDTH, BOARD_HEIGHT) dwg = svgwrite.Drawing("output.svg", size=BOARD_SIZE) dwg.viewbox(0, 0, num_x_blocks * block_sz, num_y_blocks * block_sz) dwg.defs.add(dwg.style(CSS_STYLES)) # set background dwg.add(dwg.rect(size=('100%','100%'), class_='background')) draw_board(dwg, data, block_sz) dwg.save() if __name__== '__main__': main()
输入数组为[[0, 1, 1, 0, 0], [1, 0, 1, 0, 0]]运行代码后,生成的SVG文件中相邻矩形之间出现了白色缝隙。尝试过添加stroke属性、调整边距等方案,均未达到预期效果,需要实现01数组到指定尺寸无间隙SVG方格图的转换。
解决方案
在CSS样式中添加shape-rendering: crispEdges;属性即可消除缝隙,修改后的CSS样式如下:
CSS_STYLES = """ .background { fill: white; } .blacksquare { fill: black; shape-rendering: crispEdges;} .whitesquare { fill: white; shape-rendering: crispEdges;} """
修改后即可得到无间隙的SVG方格图。
内容的提问来源于stack exchange,提问作者mrtpk
相关产品推荐
相关产品推荐

