tikz 框内文本的居中/水平对齐

tikz 框内文本的居中/水平对齐

我在将文本置于框内居中时遇到问题:

\documentclass[a4paper,fontsize=12pt,a4paper,DIV=10,BCOR=10mm,twoside,titlepage=false,openany,pagesize]{scrbook}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{blindtext}
\setkomafont{disposition}{\normalfont\bfseries}

\usepackage{tikz}
\usetikzlibrary{calc,matrix,positioning}
\begin{document}

\begin{figure}[h]
\centering
\caption{test}
\label{test}
\begin{tikzpicture}[element/.style={text width=1.8cm,minimum height=0.85cm}]
\matrix (m) [matrix of nodes,nodes={element},column sep=-\pgflinewidth, row sep=-\pgflinewidth,]{
         & Cooperate & Defect  \\
Cooperate & |[draw]|3+x,3+x & |[draw]|1+y,4 \\
Defect & |[draw]|4,1+y & |[draw]|2,2 \\
};
\node[above=0.25cm] at ($(m-1-2)!0.5!(m-1-3)$){\textbf{Actor A}};
\node[rotate=90] at ($(m-2-1)!0.5!(m-3-1)+(-1.25,0)$){\textbf{Actor B}};
\end{tikzpicture}
\end{figure}
\end{document}

答案1

align=center选项传递给节点。我还将其更改为matrix of math nodes具有适合数学表达式的数学模式(常规文本是在\textfrom的帮助下生成的amsmath),并增加了文本宽度:

    \documentclass[a4paper,fontsize=12pt,a4paper,DIV=10,BCOR=10mm,twoside,titlepage=false,openany,pagesize]{scrbook}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{blindtext}
\setkomafont{disposition}{\normalfont\bfseries}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{calc,matrix,positioning}
\begin{document}

\begin{figure}[h]
\centering
\caption{test}
\label{test}
\begin{tikzpicture}[element/.style={text width=2.5cm,minimum height=0.85cm,align=center}]
\matrix (m) [matrix of math nodes,nodes={element},column sep=-\pgflinewidth, row sep=-\pgflinewidth,]{
         & \text{Cooperate} & \text{Defect}  \\
\text{Cooperate} & |[draw]|3+x,3+x & |[draw]|1+y,4 \\
\text{Defect} & |[draw]|4,1+y & |[draw]|2,2 \\
};
\node[above=0.25cm] at ($(m-1-2)!0.5!(m-1-3)$){\textbf{Actor A}};
\node[rotate=90] at ($(m-2-1)!0.5!(m-3-1)+(-1.25,0)$){\textbf{Actor B}};
\end{tikzpicture}
\end{figure}
\end{document}

在此处输入图片描述

相关内容