我想在图形上添加图片,并且当窗口调整大小以使其保持在其位置时,我希望其与整个图形一起缩放。我尝试添加新轴(add_axis
)和annotationBboxes
,但是两种方法均失败。我可以在图上放一个图像,但是当调整窗口大小时它将移动。这是我的代码的相关片段:
class Field:
def __init__(self, cords, rgb, lettuce=True):
self.x = cords[0]
self.y = cords[1]
self.rgb = (rgb[0]/255, rgb[1]/255, rgb[2]/255)
self.lettuce = lettuce
def image(self):
import matplotlib.pyplot as plt
return plt.imread(self.__class__.__name__ + '.png', format='png')
class Board:
def __init__(self, dim):
self.dim = dim
self.all_fields = []
def add_field(self, field):
self.all_fields.append(field)
def show(self):
import matplotlib.pyplot as plt
import matplotlib.patches as pat
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')
ax.set_xlim((-1, self.dim + 1))
ax.set_ylim((-1, self.dim + 1))
plt.axis('off')
for x in range(self.dim):
for y in range(self.dim):
ax.add_patch(pat.Rectangle((x, y), 1, 1,
linewidth=1, edgecolor='k', facecolor=(1, 1, 1)))
for field in self.all_fields:
ax.add_patch(pat.Rectangle((field.x, field.y), 1, 1,
linewidth=1, edgecolor='k', facecolor=field.rgb))
im = field.image()
newax = fig.add_axes([0.12, 0.54, 0.22, 0.1], anchor='NE')
newax.imshow(im)
newax.axis('off')
if field.lettuce:
ax.add_patch(pat.Circle((field.x + 0.5, field.y + 0.5), 0.2, facecolor=(0, 1, 0)))
fig.canvas.draw()
P = Board(10)
A = Field((0, 4), (255, 106, 0))
P.add_field(A)
P.show()
所以我要添加矩形以创建网格。然后,我添加代表特定字段的彩色矩形。现在,我想用沙漠图像代替橙色矩形。最后一步是有问题的,因为很难将图像放置在正确的位置,并且在调整窗口大小时会移动。