PGF math has a width
function that measures the width of its parameter. It can be accessed with \pgfmathparse{width("some text")}
or \pgfmathwidth{"some text"}
. The result is then stored in \pgfmathresult
.
I think text centered
is a depreciated option. Using align=center
instead makes \\
work as expected.
\documentclass{book}
\usepackage{tikz}
\begin{document}
\newcommand{\MyBox}[3][XXX]{
\pgfmathwidth{"#1"}
% store the result before it gets overwritten by some internal call to `\pgfmath...`.
\let\myboxwidth\pgfmathresult
\draw (#2)
node
[rectangle,draw,minimum width=2em,minimum height=2em,
text width=\myboxwidth,
text centered, inner sep=1ex] {#3};
}
\begin{tikzpicture}
\MyBox[animals]{0,0}{animals cats \& dogs}
\MyBox[trees]{3,0}{trees oak aspen}
\draw (0,-2) node
[rectangle, draw, align=center, inner sep=1ex] {animals\\ cats \& dogs};
\draw (3,-2) node
[rectangle, draw, align=center, inner sep=1ex] {trees\\ oak aspen};
\end{tikzpicture}
\end{document}
Both of these solutions only work with TikZ/PGF version 2.10 (and higher).
I think the good package is showexpl
.This package works with listings
.
I work actually on the tkzexample package. The last version is on ctan but I try to finish the doc. You can present the source code and the result but it's not possible to highlight the syntax.
\documentclass[]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{tikz,tkzexample}
\usetikzlibrary{shapes,arrows}
\colorlet{graphicbackground}{red!10!white}%
\colorlet{codebackground}{blue!10!white}%
\colorlet{codeonlybackground}{gray!20}
\begin{document}
\parindent=0pt
\begin{tkzexample}[small,width=8cm,overhang,frame tex=red,frame code=blue]
\begin{minipage}{6cm}
\section{Minipage et èçéà\&§}
Ceci est un test pour "minipage"
\end{minipage}
\end{tkzexample}
\hspace{24pt}
\begin{tkzexample}[small,width=3cm,frame tex=red,frame code=blue]
\begin{tikzpicture}
\draw (0,0) node[circle,
shade,
ball color=Peach,minimum size=2cm]{};
\end{tikzpicture}
\end{tkzexample}
\hspace{24pt}
\begin{tkzltxexample}[line frame width=2pt]
\begin{tkzexample}[width=4cm,frame tex=red,frame code=blue]
\tikz[baseline]
\node [circle,line width=1ex,draw=blue,fill=blue]
{\textcolor{white}{\Large{TikZ}}};
\end{tkzexample}
\end{tkzltxexample}
\hspace{24pt}
\begin{tkzexample}[width=4cm,frame tex=red,frame code=blue]
\tikz[baseline]
\node [circle,line width=1ex,draw=blue,fill=blue]
{\textcolor{white}{\Large{TikZ}}};
\end{tkzexample}
\hspace{24pt}
\begin{tkzexample}[width=3cm,frame tex=red,frame code=blue]
$x \mathbin{\tikz[baseline] \draw[|->,>=triangle 45]%
(0pt,.5ex) -- (8ex,.5ex);} f(x)$
\end{tkzexample}
\end{document}
Best Answer
You can use a color box.
If you want the text to have a different color use,
For a paragraph you can you
parbox
orminipage
.If you want a bit of "padding"