# What's the best way to draw a square or rectangle with specified dimensions?

How might one define a command \rectangle, invoked via e.g.

\rectangle{70cm}{70cm}


that produces a black-outline rectangle of the specified dimensions?

-
I needed the rectangle for a MWE. I've just seen the following easy way to make a filled rectangle, which is fine for MWE purposes: \rule{<width>}{<height>} –  Mohan Dec 5 '12 at 16:49

A way without any package is the following:

\newcommand{\rectangle}[2]{{% #1 = width, #2 = height
\fboxsep=-\fboxrule\sbox0{}\wd0=#1\ht0=#2\relax\fbox{\box0}}}


With \fboxsep=-\fboxrule (that in proper LaTeX syntax would be \setlength{\fboxsep}{\fboxrule}) we ask LaTeX to draw the frame "inside the box". The box we draw is empty, but its width and height are set to the specified arguments. So we build this empty box and then we frame it.

Instead of \usebox{0} I prefer to employ the primitive command \box0, which uses the box and destroys it. Since all happens inside a group, the value of \fboxsep will be restored to what it was before and we hide our tracks also for the (scratch) box register 0.

If one wants to specify also a depth, then the extension is quite easy:

\newcommand{\rectangle}[3][0pt]{{%
\fboxsep=-\fboxrule\sbox0{}\wd0=#2\ht0=#3\dp0=#1\relax\fbox{\box0}}}


so that \rectangle{10pt}{20pt} will build a rectangle 10pt wide and 20pt high, while

\rectangle[2pt]{10pt}{18pt}


will build the same, but placed slightly below the baseline.

-
\setlength{\wd0 }{#1} and \setlength{\ht0 }{#2} would also support package calc with its expressions in the argument of \rectangle. (Note: the space after 0 is needed unless \setlength is fixed by package fixltx2e.) –  Heiko Oberdiek Dec 5 '12 at 15:01

My attempt at using picture environment,

\documentclass{article}

\newcommand{\rectangle}[2]{%
\setlength{\unitlength}{1cm}%
\begin{picture}(#1,#2)%
\linethickness{0.1mm}%
\multiput(0,0)(#1,0){2}{\line(0,1){#2}}%
\multiput(0,0)(0,#2){2}{\line(1,0){#1}}%
\end{picture}%
\setlength{\unitlength}{1pt}    % Reset unit length to 1 pt
}

\begin{document}

\rectangle{1}{4}
\rectangle{7}{2}
\rectangle{3}{3}

\end{document}

-

An alternative answer using TikZ is

\newcommand{\rectangle}[2]{\tikz \draw (0,0) rectangle (#1,#2);}


(You need to add \usepackage{tikz} in your preamble)

If you want to have a rectangle filled with black, replace \draw by \fill. You can also choose the color: for instance

\newcommand{\rectangleplus}[3]{\tikz \draw[#3] (0,0) rectangle (#1,#2);}
\rectangleplus{4cm}{0.5cm}{blue}
\rectangleplus{4cm}{0.5cm}{blue,dashed}
`

and many other things.

-