我在一个小方块网格上画了一个椭圆,我需要对椭圆内的方块进行着色,有没有办法不用对每个方块逐个进行着色?下面是我运行以下代码时得到的结果 以下是代码:
\documentclass[10pt]{article}
\usepackage{pgf,tikz}
\usepackage{mathrsfs}
\usetikzlibrary{arrows}
\pagestyle{empty}
\begin{document}
\definecolor{cqcqcq}{rgb}{0.7529411764705882,0.7529411764705882,0.7529411764705882}
\begin{tikzpicture}[line cap=round,line join=round,>=triangle 45,x=1.0cm,y=1.0cm]
\draw [color=cqcqcq,, xstep=0.2cm,ystep=0.2cm] (1.6545364855997213,0.21463161817165122) grid (10.69837464681328,7.590037566885466);
\clip(1.6545364855997213,0.21463161817165122) rectangle (10.69837464681328,7.590037566885466);
\draw [rotate around={90.:(5.,4.)}] (5.,3.) ellipse (2.5617375054936047cm and 1.6007807617074208cm);
\end{tikzpicture}
\end{document}
答案1
问题是,普通的裁剪不起作用,因为裁剪对网格一无所知。下面的示例将裁剪与椭圆组合为裁剪区域,并排除与椭圆相交的单元格。
\documentclass[10pt]{article}
\usepackage{tikz}
\usetikzlibrary{intersections}
\usepackage{xcolor}
\pagestyle{empty}
\begin{document}
\definecolor{cqcqcq}{RGB}{192,192,192}
\colorlet{square}{blue!75!white}
\begin{tikzpicture}
\def\xmin{3.8}
\def\xmax{8.2}
\def\ymin{1}
\def\ymax{7}
\def\EllipsePath{%
[rotate around={90:(5, 4)}]
(5, 3) ellipse (2.5617375054936047cm and 1.6007807617074208cm)%
}
\path[name path=ellipse]\EllipsePath;
\global\let\FillList\empty
\foreach \x in {4.4, 4.6, ..., 7.6} {
\foreach \y in {1.4, 1.6, ..., 6.4} {
\path[name path=square] (\x, \y) rectangle ++(.2, .2);
\path[name intersections={
of=ellipse and square,
total=\t,
}]
\pgfextra{
\ifnum\t=0 %
\xdef\FillList{%
\FillList
\ifx\FillList\empty\else,\fi
\x/\y%
}%
\fi
}
;
}
}
\begin{scope}
\clip\EllipsePath;
\fill[square]
\foreach \x/\y in \FillList {
(\x, \y) rectangle ++(.2, .2)
}
;
\end{scope}
\draw[color=cqcqcq, step=.2]
(\xmin, \ymin) grid (\xmax, \ymax)
(\xmin, \ymin) rectangle (\xmax, \ymax)
;
\clip (\xmin, \ymin) rectangle (\xmax, \ymax);
\draw\EllipsePath;
\end{tikzpicture}
\end{document}
注意:编译需要相当长的时间。