根据形状的宽度调整其颜色!在 tikz 中

根据形状的宽度调整其颜色!在 tikz 中

我想画一个图形。我想调整图形中的颜色。我想设置如果minimum width每个形状的值小于 5,则其颜色应为绿色!5。如果最小宽度为 5< 且 <10,则颜色应为绿色!50。我有数千个这样的图形,这对我来说真的很重要。你有什么解决方案吗?谢谢,这是我的简单代码;

\documentclass{article}
\usepackage{tikz}

%% setting shekl
\newcommand\hight{0.9}
\newcommand\val{50}
\newcommand\mycolor{green}

\newcommand\widthdirect{3} 
\newcommand\widthback{14}



\begin{document}
\centering
\begin{tikzpicture}[
font=\sf \scriptsize,
>=LaTeX,
background/.style={rectangle, minimum height =\hight cm,minimum width=\widthback cm, rounded corners=4.4mm, fill=black!10, draw,thick,},
direct/.style={rectangle, minimum height =\hight cm, rounded corners=4.4mm, minimum width=\widthdirect cm, fill=green!10, draw,thick,},
]


\node [background] at (0,1){} ;
\node [direct] at (0,1){} ;


\end{tikzpicture}

\end{document}

答案1

从提供的信息很难准确把握哪种方法最适合您的用例,但一种方法可能是定义一个命令来执行设置正确颜色百分比的逻辑。当然,我建议这样做,因为我看到您定义了一些包含宽度的命令,并将其交给。如果要遍历任意数量的绘制形状,推断出每个绘制节点的最小宽度,然后根据需要设置颜色,minimum width那将是一个完全不同的故事。tikzpicture

\documentclass{article}
\usepackage{tikz}

\newcommand\widthdirect{3}
\newcommand{\colPerc}[1]{%
    \ifnum#1<5
        5%
    \else
        \ifnum#1<10
            50%
        \else
            100%
        \fi
    \fi%
}

\begin{document}
    \centering
    \begin{tikzpicture}[direct/.style={rectangle, minimum height=0.9cm,
                                       rounded corners=4.4mm, minimum width=\widthdirect cm,
                                       fill=green!\colPerc{\widthdirect}, draw,thick,}]
        \node [direct] at (0,1){} ;
    \end{tikzpicture}

    \renewcommand\widthdirect{8}

    \begin{tikzpicture}[direct/.style={rectangle, minimum height=0.9cm,
                                       rounded corners=4.4mm, minimum width=\widthdirect cm,
                                       fill=green!\colPerc{\widthdirect}, draw,thick,}]
        \node [direct] at (0,1){} ;
    \end{tikzpicture}

    \renewcommand\widthdirect{12}

    \begin{tikzpicture}[direct/.style={rectangle, minimum height=0.9cm,
                                       rounded corners=4.4mm, minimum width=\widthdirect cm,
                                       fill=green!\colPerc{\widthdirect}, draw,thick,}]
        \node [direct] at (0,1){} ;
    \end{tikzpicture}
\end{document}

当然,这是非常基础的,根据您的需要,您可以将 TikZ 风格提取为更精致、更全球化的风格。

如图

相关内容