使用宏进行绘图

使用宏进行绘图

我刚刚开始使用 MetaPost,我希望能够在我的图像上放置网格,这样我就可以轻松地从中读取坐标。我想编写一个宏,在创建新图形时可以导入它,然后使用单个命令绘制网格。

我的网格宏如下:

def drawgrid(expr width, height, nx, ny) = 
begingroup
ny * u = width;
nx * v = height;
lu = 2 * u;
lv = 2 * v;
my = floor(width / lu);
mx = floor(height / lv);

for y = 0 upto nx:
    draw (0,y*v)--(width,y*v);
endfor
for y = 0 upto mx:
    draw (0,y*lv)--(width,y*lv) withpen pencircle scaled 2;
    label(decimal(y*lv/v), (-0.5u, y*lv));
endfor

for x = 0 upto my:
    draw (x*lu,0)--(x*lu,height) withpen pencircle scaled 2;
    label(decimal(x*lu/u), (x*lu, -0.5v));
endfor
for x = 0 upto ny:
    draw (x*u,0)--(x*u,height);
endfor
endgroup
enddef;
end

当从同一个文件 (grid.mp) 调用时,它工作正常,但如果我从另一个图形调用它,则无法绘制任何内容。我的其他图形代码是:

input grid

beginfig(1); textwidth := 345.0;
width := 0.5textwidth;
radius := 0.25width;

fill fullcircle scaled radius withcolor blob;
draw fullcircle scaled radius withcolor blobBorder;
clip currentpicture to (-0.5,-0.5)--(-0.5,0.5radius+0.5)--(0.5radius+0.5,0.5radius+0.5)--(0.5radius+0.5,-0.5)--cycle;
draw (-0.5, 0.5radius)--(-0.5, -0.5)--(0.5radius, -0.5) withcolor blobBorder;
draw (0, 0)--(0.25radius, 0.45radius);
drawgrid(width,width,2,2);
endfig
end

它没有绘制任何东西(甚至没有生成 .1 文件)。我做错了什么?

答案1

以下是我评论后的宏文件:

def drawgrid(expr width, height, nx, ny) = 
begingroup
  save u, v, mx, my, lv, lu;
  ny * u = width;
  nx * v = height;
  lu = 2 * u;
  lv = 2 * v;
  my = floor(width / lu);
  mx = floor(height / lv);

  for y = 0 upto nx:
    draw (0,y*v)--(width,y*v);
  endfor
  for y = 0 upto mx:
    draw (0,y*lv)--(width,y*lv) withpen pencircle scaled 2;
    label(decimal(y*lv/v), (-0.5u, y*lv));
  endfor

  for x = 0 upto my:
    draw (x*lu,0)--(x*lu,height) withpen pencircle scaled 2;
    label(decimal(x*lu/u), (x*lu, -0.5v));
  endfor
  for x = 0 upto ny:
    draw (x*u,0)--(x*u,height);
  endfor
endgroup
enddef;

下面是一个产生某些内容的主文件(不确定绘图是否符合预期):

input grid;

beginfig(1); 
textwidth := 345.0;
width := 0.5textwidth;
radius := 0.25width;
color blob, blobBorder; blob=red; blobBorder = blue;
draw fullcircle scaled radius withcolor blob;
draw fullcircle scaled radius withcolor blobBorder;
clip currentpicture to (-0.5,-0.5)--(-0.5,0.5radius+0.5)--(0.5radius+0.5,0.5radius+0.5)--(0.5radius+0.5,-0.5)--cycle;
draw (-0.5, 0.5radius)--(-0.5, -0.5)--(0.5radius, -0.5) withcolor blobBorder;
draw (0, 0)--(0.25radius, 0.45radius);
drawgrid(width,width,2,2);
endfig;
end;

结果:

在此处输入图片描述

相关内容