I want to fill a tikz-picture with a pattern, based on an external picture.
Is this possible? If yes, how?
I tried to define a new pattern with \pgfdeclarepatternformonly
, but \pgfuseimage
seems to be no valid command inside \pgfdeclarepatternformonly
.
Remark:
- In my example I used a marble-picture, but my question is independend from this special picture.
- I force the tile to 1cm. Probably it would be better to use the real size of the tile image.
- If I define
\pgfdeclarepatternformonly
after\begin{document}
the LaTeX error disappear, but the pattern does not work.
My MNWE (minimal not working Example):
\documentclass[]{standalone}
\usepackage{tikz}
\usetikzlibrary{patterns}
%Source: http://upload.wikimedia.org/wikipedia/de/thumb/f/f9/LapG.jpg/83px-LapG.jpg
%But could be any other picture
\pgfdeclareimage[width=1cm,height=1cm]{marble}{83px-LapG}%force quadratic tile
\pgfdeclarepatternformonly{marble}{\pgfpoint{0cm}{0cm}}{\pgfpoint{1cm}{1cm}}{\pgfpoint{1cm}{1cm}}{
\pgfuseimage{marble}%! LaTeX Error: Missing \begin{document}.
}
\begin{document}
\begin{tikzpicture}
% This should create a rectangle with 15*15 tiles.
\draw[pattern=marble] (0,0) rectangle (15,15);
\end{tikzpicture}
\end{document}
Best Answer
It is not possible with
pattern
, but with thepath picture
key and a few calculations.I have used patterns available at texture-s.blogspot.de.
I have turned the code into a small TikZ library and added a macro and two keys:
\pgfSetupImageAsPattern[<opt arguments for \pgfdeclareimage>]{<name>}{<path/file>}
is a wrapper for
\pgfdeclareimage
but also automatically measures the resulting image (if only one of the dimensions (width
andheight
) is given, PGF keeps the aspect ratio of the image, but it is not accessible for the user).use image as pattern=<name>
sets up the pattern
<name>
for use with the keyimage as pattern
. This key is intended to set the image scope-wide. It can also be used at every path, though it may be preferable to setup an own style:and then simply use
\path[marble] …;
.image as pattern=<opt arguments for \pgftext>
actually uses the previously set
<name>
pattern. The key accepts one optional argument that is forwarded to the internally used\pgftext
.The placing of these images starts with one image centered on the south west point of the path. This can be changes by the optional argument to
image as pattern
as shown in the two latter examples of the document below.As this is hardly noticeable with white-noise-ish marble patterns I have used the following image to show this:
Keys useable for
\pgftext
arecenter
(default),left
,right
,top
,bottom
,base
(=bottom
as PGF images do not have a depth),x
,y
(similar toxshift
andyshift
), androtate
(needs manual adjusting withpatterns.image
).Code
Library
tikzlibrarypatterns.image.code.tex
Test file
Output 1
Output 2