![Tikz:在某个形状内画一条线](https://linux22.com/image/380662/Tikz%EF%BC%9A%E5%9C%A8%E6%9F%90%E4%B8%AA%E5%BD%A2%E7%8A%B6%E5%86%85%E7%94%BB%E4%B8%80%E6%9D%A1%E7%BA%BF.png)
下图说明了一切。如何才能有效地实现红色虚线?
下面的丑陋代码是我目前得到的。
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\draw (-3, -3) grid (5, 5);
\draw[dashed, color=red] (0+0.1, 0-0.1) -- (1+0.1, 0-0.1) -- (1+0.1, 2-0.1)-- (2+0.1, 2-0.1) -- (2+0.1, 4-0.1) -- (3-0.1, 4-0.1) -- (3-0.1, 1+0.1) -- (2-0.1, 1+0.1) -- (2-0.1, -1+0.1) -- (0+0.1, -1+0.1) -- (0+0.1, 0-0.1);
\end{tikzpicture}
\end{document}
答案1
欢迎来到 TeX.SE!是的,你可以简化事情,因为你只需要指定更少的坐标。你的轮廓将归结为
\path[Outline={distance 0.45cm and style {draw=red,dashed}}]
(0.05,-0.5) -- ++(1.45,0) -- ++(0,2)
--++ (1,0) -- ++(0,2.45);
你付出的代价就是你需要做一些准备。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{decorations}
% based on https://tex.stackexchange.com/a/103088/121799
% and https://tex.stackexchange.com/a/423581/121799
\def\pgfdecoratedcontourdistance{0pt}
\pgfkeys{/pgf/decoration/contour distance/.code={%
\pgfmathparse{#1}%
\let\pgfdecoratedcontourdistance=\pgfmathresult},%
/pgf/decoration/contour name/.store in=\ContourName,
/pgf/decoration/contour name=mycontour
}
\pgfdeclaredecoration{contour lineto}{start}
{
\state{start}[next state=draw, width=0pt]{
\pgfcoordinate{\ContourName-0}{\pgfpoint{0pt}{\pgfdecoratedcontourdistance}}
\pgfpathlineto{\pgfpoint{0pt}{\pgfdecoratedcontourdistance}}%
}
\state{draw}[next state=draw, width=\pgfdecoratedinputsegmentlength]{
\pgfmathparse{-\pgfdecoratedcontourdistance*cot(-\pgfdecoratedangletonextinputsegment/2+90)}%
\let\shorten=\pgfmathresult%
\pgfpathlineto{\pgfpoint{\pgfdecoratedinputsegmentlength+\shorten}{\pgfdecoratedcontourdistance}}%
%\stepcounter{Outline}
\pgfcoordinate{\ContourName-1}{\pgfpoint{\pgfdecoratedinputsegmentlength+\shorten}{\pgfdecoratedcontourdistance}}
}
\state{final}{
\pgfpathlineto{\pgfpoint{\pgfdecoratedinputsegmentlength}{\pgfdecoratedcontourdistance}}%
\pgfpathlineto{\pgfpoint{\pgfdecoratedinputsegmentlength}{0pt}}
}
}
\tikzset{Outline/.style args={distance #1 and style #2}{ postaction={
decoration={contour lineto, contour distance=-#1,contour name=mycontourA},
#2,decorate},
postaction={
decoration={contour lineto, contour distance=#1,contour name=mycontourB},
#2,decorate},}}
\begin{document}
\begin{tikzpicture}
\draw (-3, -3) grid (5, 5);
\path[Outline={distance 0.45cm and style {draw=red,dashed}}]
(0.05,-0.5) -- ++(1.45,0) -- ++(0,2)
--++ (1,0) -- ++(0,2.45);
\end{tikzpicture}
\end{document}