[Tex/LaTex] Color background of chapter headings

chapterscolorsectioningtitlesec

I'm trying to change the background color of the chapter headings. I'd like the full top part of the page, including top and right margins to turn gray until the titlerule.

Currently they look like this:

\documentclass[10pt,twoside,openright]{book}
\usepackage{titlesec}
\titleformat{\chapter}[display]{\LARGE\sffamily\bfseries\raggedright}
  {\leftskip2cm {\Large\textmd{\chaptertitlename~\thechapter}}}
{0cm}{\leftskip2cm}[\vspace{4mm} {\color{dgray}\titlerule[.6mm]} \enlargethispage{-\parskip}]

The \enlargethispage is used to make some extra space for the title number, which appears at the bottom of the page only at the first page of the chapter. My attempts with using the framed environment or colorbox have so far not been successful.

Best Answer

Because there were quite a lot of changes following your request from my other answer, I decided to write a new one instead of editing my old answer. Here you go.

I took the macro definitions of \blap and \tlap from here: google-groups

\documentclass[10pt,twoside,openright]{book}
\usepackage[explicit]{titlesec}
\usepackage{color}
\usepackage{eso-pic}
\usepackage{geometry}

\newcommand\chapterBox{%
  \put(0,0){%
    \parbox[b][\paperheight]{\paperwidth}{%
      \color{blue}\rule{\paperwidth}{8.1cm}
      \vfill
    }
}}

\def\tlap#1{\vbox to 0pt{\vss#1}}
\def\blap#1{\vbox to 0pt{#1\vss}}

\titleformat{\chapter}[display]
            {\LARGE\sffamily\bfseries\raggedright}
            {}
            {0cm}
            {\AddToShipoutPicture*{\chapterBox}
              \tlap{\parbox[b]{\linewidth}{%
                  \Large\textmd{\chaptertitlename~\thechapter}\newline
                  \Huge\bfseries #1
              }}
            }
            [{\color{red}\titlerule[.6mm]}\enlargethispage{-\parskip}]

\begin{document}
\chapter{My chapter}

text

\chapter{My extremely long second chapter heading}

\chapter{My last and even longer chapter heading that is so long, it does actually span three lines}

text

\clearpage

text

\end{document}