
我正在嘗試使用 LaTeX 在我的論文上創建一個等邊三角形,但我不明白 tikz (或 tikzpicture)如何選擇其座標的原點(0,0)在哪裡。寫完一段文字後,我想用以下程式碼在紙張的右側繪製三角形:
\documentclass[12pt,a4paper]{article}
\usepackage{tikz}
%parameters are the following : cooX , cooY , triangleSize
\newcommand{\triangle} [3] {
\begin{tikzpicture}
\draw (#1,#2)--(#1+0.5*#3,#2+0.86*#3)--(#1+1*#3,#2)--cycle;
\end{tikzpicture}
}
\begin{document}
\normalsize
Here is my text and the triangle
\triangle {10}{0}{3}
\end{document}
這將創建:
我的目標是透過呼叫函數將三角形向右繪製 10 厘米\三角形第一個參數{10}。正如您在我的程式碼中看到的,我希望在我已經選擇的座標 (10,0) 上繪製三角形的第一個點,這是我的 newcommand 的參數\三角形。問題是,無論我對參數做什麼,原點總是相同的。如果我輸入,結果會是一樣的{20}代替{10},我希望它根據我的參數向右移動 10 或 20 公分。另一方面,如果我用一個數字更改參數,而該數字不是我在呼叫 newcommand 時選擇的數字,如下所示:
...
\draw (20,#2)--(#1+0.5*#3,#2+0.86*#3)--(#1+1*#3,#2)--cycle;
...
\triangle {10}{0}{3}
...
(我將此程式碼中的第一個 #1 更改為 20,將 10 替換為 20)。
然後 tikz 考慮到這一變化並顯示一個變形的三角形,起點位於最右側:
這就好像 tikz 總是想將原點放在同一個地方,無論我加到座標中的常數(#1 和 #2)是什麼。為了根據我給新命令的參數移動我的三角形,我必須做什麼\三角形?
答案1
您應該注意一些方面,排名不分先後。首先讓我們來看看下面程式碼的截圖。
(1) 白色三角形來自您的宏,程式碼本身有些差異。依照慣例,鍵入的換行符(實際上是空白行)會建立一個新行類型集。
(2) LaTeX 是排版,而不是打字,正如您從 Word 或其他編輯器中可能知道的那樣。它嘗試對實體進行排版。在你的情況下,這些是:
- 單一字符,包括空格
- 創建的東西
\newcommand
(白色三角形) - 還可以有更多
想像每個字母或三角形周圍有一個盒子,用鉛製成,就像古騰堡的舊時代或你過去的當地報紙一樣。
LaTeX 將繼續將實體黏合在一起,直到完成,嘗試實現它「知道」的「良好的排版結果」。
(3) 眾所周知,a 內每行的最後一個字元\newcommand
應以 a 結尾%
(即將該行的其餘部分註解掉)。如果你錯過了,LaTeX 會嘗試排版你不想要的空間(簡化的)。
(4) 我的三角形的兩種變體,青色和黃色,差別如下:
- 青色的水平空間(您尋求的偏移)為 7 厘米(如果是 10 厘米,則差異不會足夠明顯)通過
\hspace{}
- 黃色
\hfill
則使用:它將“塊”移動到此處的最外面。
(5) 請認可我的歐洲選擇\documentclass
;-)
\documentclass[12pt,a4paper]{article}
\usepackage{tikz}
%parameters are the following : cooX , cooY , triangleSize
\newcommand{\trngl}[3]{%
\begin{tikzpicture}%
\draw (#1,#2)--(#1+0.5*#3,#2+0.86*#3)--(#1+1*#3,#2)--cycle;%
\end{tikzpicture}%
}
\newcommand{\trnglA}[3]{%
\hspace{7cm}\begin{tikzpicture}% <<< 7cm to see the difference
\draw[fill=teal!20] (#1,#2)--(#1+0.5*#3,#2+0.86*#3)--(#1+1*#3,#2)--cycle;%
\end{tikzpicture}%
}
\newcommand{\trnglB}[3]{%
\hfill\begin{tikzpicture}%
\draw[fill=yellow!20] (#1,#2)--(#1+0.5*#3,#2+0.86*#3)--(#1+1*#3,#2)--cycle;%
\end{tikzpicture}%
}
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\begin{document}
\normalsize
% ~~~ variations of your code: WATCH the differences ~~~~~~~~~~~~~~~~~~
Here is my text and the \textbf{triangle} on same line \trngl{10}{0}{3}
Here is my text and the \textbf{triangle} still on same line
\trngl{10}{0}{3}
Here is my text and the \textbf{triangle} on next line
\trngl{10}{0}{3}
% ~~~ using some (hopefully correct) \hspace{} ~~~~~~~~~~~~~~
Here is my text and the \textbf{triangleA} on next line
\trnglA{10}{0}{3}
% ~~~ using \hfill ~~~~~~~~~~~~~~~~~~~~
Here is my text and the \textbf{triangleB} on next line
\trnglB{10}{0}{3}
\end{document}