On page 628 of the TikZ manual, it describes how to code the text
anchor for a custom shape so that the label text is placed with its centre at the origin. I've done this to create a simple shape, which draws a square of side length 10pt. The text label should then be centered at the origin.
However, it doesn't seem to work correctly. Here's a screenshot:
On the left is a node defined with my new shape, with label \fbox{$f$}
. On the right is a standard TikZ node with the same label, created with the draw
option and inner sep=1pt
. Both nodes are positioned with the same y coordinate - but clearly, the label for my shape hasn't been placed at the same height, and it is clearly not correctly centred in its box.
Question: how can I get the text label for a custom shape properly centred at the origin?
Here's the code.
\documentclass{article}
\usepackage{tikz}
\makeatletter
\pgfdeclareshape{myshape}
{
\savedanchor\centerpoint
{
\pgf@x=0pt
\pgf@y=0pt
}
\anchor{center}{\centerpoint}
\anchorborder{\centerpoint}
\savedanchor{\upperrightcorner}
{
\pgf@y=.5\ht\pgfnodeparttextbox
\pgf@x=.5\wd\pgfnodeparttextbox
}
\anchor{text}
{
\upperrightcorner
\pgf@x=-\pgf@x
\pgf@y=-\pgf@y
}
\backgroundpath
{
\pgfsetstrokecolor{black}
\pgfpathmoveto{\pgfpoint{-5pt}{-5pt}}
\pgfpathlineto{\pgfpoint{-5pt}{5pt}}
\pgfpathlineto{\pgfpoint{5pt}{5pt}}
\pgfpathlineto{\pgfpoint{5pt}{-5pt}}
\pgfpathclose
\pgfusepath{stroke}
}
}
\makeatother
\begin{document}
\setlength\fboxsep{0pt}
\begin{tikzpicture}
\node [myshape] at (0,0) {\fbox{$f$}};
\node [draw, inner sep=1pt, red] at (12pt,0) {\fbox{$f$}};
\end{tikzpicture}
\end{document}
depth
dependence (Try it with different characters likeh
org
. Add\advance\pgf@y by -.5\dp\pgfnodeparttextbox%
to thesavedanchor
part (just like in the manual). This centers but does not solve everything though. You still need to modify the rectangle further. – percusse Jan 28 '12 at 0:26