[Tex/LaTex] How to change the shaded color of the \rule{…}{…} command

colorrules

To change the shaded color of the \rule{...}{...} command, one solution is

\textcolor‎{‎blue‎}{\rule{2cm}{2cm}}‎

but I want to know how can I directly change the color of this command globally?

Best Answer

You could do

\makeatletter
\let\old@rule\@rule
\def\@rule[#1]#2#3{\textcolor{blue}{\old@rule[#1]{#2}{#3}}}
\makeatother

But it may be better to instead define a new \colorrule command and use that instead, as you may find \rule is used in unexpected places so if you redefine it you may be changing more than you want to change.


If you need to override this sometimes it's probably better to use a colour such as rulecolor rather than blue that you can (re)define when needed:

enter image description here

\documentclass{article}

\usepackage[dvipsnames]{color}

\makeatletter
\let\old@rule\@rule
\def\@rule[#1]#2#3{\textcolor{rulecolor}{\old@rule[#1]{#2}{#3}}}
\makeatother

\definecolor{rulecolor}{named}{Blue}

\usepackage{color}

\begin{document}

\rule{1cm}{1cm}

\bigskip

\rule{.1cm}{1cm}

\bigskip

{\definecolor{rulecolor}{named}{Red}\rule{1cm}{1cm}}

\bigskip

\rule{1cm}{1cm}


\end{document}