[Tex/LaTex] How to diagonally divide a table cell … properly

makecelltablestikz-pgf

There have been many threads discussing solutions to the task of drawing a diagonal line in a table cell. There are also two packages to do this, slashbox and the better looking makecell with its \diaghead command. Apparently, better looking doesn't mean good looking though.
I just stole a MWE from one of the threads: https://tex.stackexchange.com/a/11694/13450

\documentclass{standalone}
\usepackage{makecell}
\begin{document}
\begin{tabular}{|l|c|c|}\hline
\diaghead{\theadfont Diag ColumnmnHead II}%
{Diag\\Column Head I}{Diag Column\\Head II}&
\thead{Second\\column}&\thead{Third\\column}\\
\hline
& foo & bar \\
\hline
\end{tabular}
\end{document}

Which yields this:

result from MWE

Looks more or less fine at first glance at this low resolution (which is not always the case BTW) but with a better resolution, the lower right corner looks somewhat awkward:

the line end point does not seem to lie in the line crossing

These things even show in print and it doesn't look like being off by just one pixel so it's probably not just a rendering problem.

Does anyone know why this happens and how to prevent it? (Preferably without drawing the whole table as a TikZ picture as has been suggested.)


Edit in response to Joseph's answer:

This TikZ solution by Leo Liu also has similar issues https://tex.stackexchange.com/a/17748

TikZ screenshot with two end sticking out

It appears to be rather manual, too, so maybe it's just a calibration issue. But is it really necessary to go down to the 6400% level in Adobe Reader to fine-tune parameters every time you change the content of the "diagonal cell" (for lack of a better word)?

Best Answer

The tikz solution given in Diagonal lines in table cell by Leo Liu can be fixed by taking into account the width of the node borders (even if those borders are not drawn).

The following MWE gives the right result:

\documentclass[11pt]{article}
\usepackage[T1]{fontenc}
\usepackage{array}
\usepackage{makecell}
\newcolumntype{x}[1]{>{\centering\arraybackslash}p{#1}}
\usepackage{tikz}
\newcommand\diag[4]{%
  \multicolumn{1}{p{#2}|}{\hskip-\tabcolsep
  $\vcenter{\begin{tikzpicture}[baseline=0,anchor=south west,inner sep=#1]
  \path[use as bounding box] (0,0) rectangle (#2+2\tabcolsep,\baselineskip);
  \node[minimum width={#2+2\tabcolsep-\pgflinewidth},
        minimum  height=\baselineskip+\extrarowheight-\pgflinewidth] (box) {};
  \draw[line cap=round] (box.north west) -- (box.south east);
  \node[anchor=south west] at (box.south west) {#3};
  \node[anchor=north east] at (box.north east) {#4};
 \end{tikzpicture}}$\hskip-\tabcolsep}}

\begin{document}
\setlength{\extrarowheight}{0.1cm}
\begin{tabular}{|x{0.5cm}|x{0.5cm}|x{0.5cm}|x{0.5cm}|x{0.5cm}|}\hline
&&&&20\\ \hline
&&&&30\\ \hline
&&&&45\\ \hline
15&12&18&50&\diag{.1em}{.5cm}{$a_i$}{$b_j$}\\ \hline
\end{tabular}
\end{document}

Detail:

Detail