我正在制作一个 tikz 库,我想使用一个可选参数。到目前为止,我有以下代码
该tikzlibraryquestion.code.tex
文件是
\usepackage{question}
\tikzset{
question/.pic={
\question@draw
},
}
有一个question.sty
文件
\ProvidesPackage{question}
\RequirePackage{tikz}
\newcommand*{\mycircle}[1][]{
\tikzset{%
/mycircle/.cd,#1}\mycircle@draw%
}
\tikzset{
/mycircle/.cd,
/mycircle/tilt/.code = 0 \def\mycircle@tilt{#1},
}
\def\mycircle@draw{
\draw (0, 0) circle (1);
\begin{scope}[rotate=\mycircle@tilt]
\draw (0, 0) -- (0, 1);
\end{scope}
}
最后,使用示例
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{question}
\begin{document}
\begin{tikzpicture}
\mycircle[tilt=23]
\end{tikzpicture}
\begin{tikzpicture}
\mycircle
\end{tikzpicture}
\end{document}
我如何更改.sty
文件以使tilt
参数成为可选的?
答案1
您只需使用pic
.即可pic
实现这一点。
\documentclass{standalone}
% you can put the following three lines in a package, of course
\usepackage{tikz}
\tikzset{pics/my circle/.style={code={
\draw (0,1) -- (0, 0) circle [radius=1];}}}
\begin{document}
\begin{tikzpicture}
\pic[rotate=23]{my circle};
\end{tikzpicture}
\begin{tikzpicture}
\pic{my circle};
\end{tikzpicture}
\begin{tikzpicture}
\pic[red,dashed,scale=2,rotate=-33]{my circle};
\end{tikzpicture}
\end{document}
如您所见,您可以根据需要添加任意数量的可选参数。
如需更多高级选项,请使用 pgf 键。例如:
\documentclass{standalone}
% you can put the following three lines in a package, of course
\usepackage{tikz}
\tikzset{pics/my circle/.style={code={%
\tikzset{my circle/.cd,#1}%
\def\pv##1{\pgfkeysvalueof{/tikz/my circle/##1}}%
\draw[pic actions,my circle/line] (0,1) -- (0, 0);
\draw[pic actions,my circle/circle] (0,0) circle [radius=1];}},
my circle/.cd,line/.style={},circle/.style={}}
\begin{document}
\begin{tikzpicture}
\pic[rotate=23]{my circle};
\end{tikzpicture}
\begin{tikzpicture}
\pic{my circle={line/.style={dashed,thick,blue}}};
\end{tikzpicture}
\begin{tikzpicture}
\pic[rotate=123,red] {my circle={line/.style={dashed,thick,blue}}};
\end{tikzpicture}
\begin{tikzpicture}
\pic[red,dashed,scale=2,rotate=-33]{my circle};
\end{tikzpicture}
\end{document}