我想在网格上画一堵墙。目前我有这:
%based on https://tex.stackexchange.com/a/91429/69931
\documentclass[usenames,dvipsnames]{article}
\usepackage{tikz}
\usetikzlibrary{backgrounds}
\usepackage{graphicx}
\usepackage[margin=0cm,nohead]{geometry}
\usepackage[active,tightpage]{preview}
\PreviewEnvironment{tikzpicture}
\usetikzlibrary{fit}
% Some customizable styles
\tikzset {
highlight/.style = {yellow, opacity=0.3},
digit/.style = {minimum height = 5mm, minimum width=5mm, anchor=center },
circle/.style = {draw=green!80!black, dotted, very thick},
circle number/.style = {draw=#1,very thick},
cross/.style = {red, opacity=.5, shorten >=1mm, shorten <=1mm, very thick, line cap=round},
hint/.style={blue, font=\sf, minimum width=3mm, minimum height=3mm}
}
\newcounter{hi}
\setcounter{hi}{5}
\newcounter{row}
\newcounter{col}
\newcommand\setrow[9]{
\setcounter{col}{1}
\foreach \n in {#1, #2, #3, #4, #5, #6, #7, #8, #9} {
\edef\x{\value{col} - 0.5}
\edef\y{\value{hi} + 0.5 - \value{row}}
\node[digit,name={\arabic{row}-\arabic{col}}] at (\x, \y) {\n};
\stepcounter{col}
}
\stepcounter{row}
}
\def\wallcells#1{
\node[draw=black,thick, fill=black!50, opacity=0.5, fit=#1,inner sep=0pt] {};
}
\begin{document}
\begin{tikzpicture}[scale=.5]
\begin{scope}
\draw (0, 0) grid (9, \value{hi});
\setcounter{row}{1}
\setrow {}{}{} {}{}{} {}{}{}
\setrow {}{}{} {}{}{} {}{}{}
\setrow {}{}{} {}{}{} {}{}{}
\setrow {}{}{} {}{}{} {}{}{}
\setrow {}{}{} {}{}{} {}{}{}
\end{scope}
\wallcells{(1-3) (1-6)}
\wallcells{(1-5) (3-5)}
\end{tikzpicture}
\end{document}
答案1
我不知道有任何自动解决方案可以解决这个叠加问题。但是这里有一个手动解决方案。
网格用 绘制matrix of empty nodes
。要填充的节点在 内.list
用特定的声明style
。最后,使用围绕已填充矩阵节点的垂直线段手动绘制边框。
\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}[
mygrid/.style={
matrix of nodes,
nodes in empty cells,
nodes={draw, minimum size=1cm},
column sep=-\pgflinewidth,
row sep=-\pgflinewidth},
myset/.style args= {(#1,#2)}{%
row #1 column #2/.style={nodes={fill=red!30, opacity=.5}}}
]
\matrix (A) [mygrid, myset/.list={(1,3),(1,4),(1,5),(1,6),(2,5),(3,5)}]{
&&&&&&&&\\
&&&&&&&&\\
&&&&&&&&\\
&&&&&&&&\\
&&&&&&&&\\
};
\draw[opacity=.5, ultra thick, red] (A-1-3.north west)-|
(A-1-6.south east)-|
(A-3-5.south east)-|
(A-1-5.south west)-|cycle;
\end{tikzpicture}
\end{document}