[Tex/LaTex] Alternating Background Image for different chapters in Memoir

backgroundsmemoir

I have used a background image throughout my book. The code I used evolved from this question and answer (thanks to @GonzaloMedina): "Margin vertical rule on outside margin of twosided memoir"

My question is I would like to figure out how to shift the colored background box to a new location down the edge of the page for each chapter (7-10 chapters). In addition I want to place the chapter # within the colored box. Is this possible?

    \documentclass[a4paper,openany]{book}
\usepackage[contents={},opacity=0.5,scale=1,angle=90,hshift=-2.5cm]{background}
\usepackage{lipsum}

\newcommand*\VerBar[2]{%
  {\color{#1}\rule{#2}{65pt}}}

\newif\ifBgUse

\AddEverypageHook{%
\ifBgUse%
\ifodd\value{page} 
\backgroundsetup{position={current page.north east},vshift=32.5pt,%
contents={\VerBar{blue}{5cm}}}%
\else
\backgroundsetup{position={current page.north west},vshift=-32.5pt,%
contents={\VerBar{blue}{5cm}}}%
\fi%
\BgMaterial%
\fi}

\begin{document}

\chapter{Test chapter one}
\lipsum[1-9]\clearpage

\BgUsetrue% activate background material
\chapter{Test chapter two}
\lipsum[1-9]\clearpage

\BgUsefalse% deactivate background material
\chapter{Test chapter two}
\lipsum[1-9]

\end{document}

Best Answer

You can simply introduce an appropriate horizontal shifting (since the material has previously been rotated), based, for example, on the chapter counter:

\documentclass[a4paper,openany]{book}
\usepackage[contents={},opacity=0.5,scale=1,angle=90]{background}
\usepackage{graphicx}
\usepackage{lipsum}
\usepackage{etoolbox}

\newcounter{mychap}
\pretocmd{\chapter}{\stepcounter{mychap}}{}{}

\newcommand*\VerBar[2]{%
  {\color{#1}\rule{#2}{65pt}}%
  \llap{\rotatebox[origin=c]{-90}{%
    \hspace*{-2.5cm}\raisebox{-2.5cm}[0pt][0pt]{%
      \Huge\color{white}\bfseries\thechapter}%
    }%
  }%
}

\newif\ifBgUse

\newlength\LabelSize
\setlength\LabelSize{2.5cm}

\AddEverypageHook{%
\ifBgUse%
\ifodd\value{page} 
\backgroundsetup{
  position={current page.north west},
  vshift=-32.5pt,
  hshift=-\value{mychap}*\LabelSize,
  contents={\VerBar{blue}{5cm}}%
  }%
\else
\backgroundsetup{
  position={current page.north east},
  vshift=32.5pt,
  hshift=-\value{mychap}*\LabelSize,
  contents={\VerBar{blue}{5cm}}%
  }%
\fi%
\BgMaterial%
\fi}

\begin{document}

\chapter{Test chapter one}
\lipsum[1-9]\clearpage

\BgUsetrue% activate background material
\chapter{Test chapter two}
\lipsum[1-9]

\chapter{Test chapter three}
\lipsum[1-9]

\chapter{Test chapter four}
\lipsum[1-9]\clearpage

\appendix

\chapter{Test appendix one}
\lipsum[1-9]\clearpage

\BgUsefalse% deactivate background material
\chapter{Test appendix two}
\lipsum[1-9]

\end{document}

enter image description here