MATLAB如何在两个颜色间产生任意多个过渡色?

2025-10-12 14:23:05

1、目的:计算[R1, G1, B1]、[R2, G2, B2]两种颜色的N个过渡色

思路:

1.两种[R1, G1, B1]、[R2, G2, B2]颜色对应三维RGB空间中的两个点;

2.两点坐标之差[R2-R1, G2-G1, B2-B1]即为一向量V;

3.通过将向量V分为N-1段,V/(N-1);

4.则颜色[R1, G1, B1]+(i-1)*V/(N-1)表示将两个颜色间分为N个过渡色的第i个颜色;

5.上式当i=1,即为[R1, G1, B1]。当i=N,即为[R2, G2, B2]。

2、过渡颜色计算子程序如下:

%Matlab codes

%

function ResultColor=Transition_Two_Color(Color1,Color2,N)

%Transition_Two_Color()

%    This function is used to calculate the linear transition color between two colors.

%    The generated color gradually changes from the first color to the second color.

%Input:

%    Color1, 

%          initial color, 1x3 matrix,RGB or HSV, such as [55,130,189]

%    Color2, 

%          end color, 1x3 matrix,RGB or HSV, such as [235,25,28]

%    N,

%          positive integer, number of transition,such as 4

%Output:

%    ResultColor,

%         Nx3 matrix, the first line is the initial color, the last line is the end color

%

%

   quiverC1C2=(Color2-Color1)/(N-1);%每一小段的增量

   ResultColor=zeros(N,3);%每一行代表一个过渡颜色,第一行代表初始颜色,最后一行代表末端颜色

   for i=1:N

       ResultColor(i,:)=Color1+quiverC1C2*(i-1);%所有颜色

   end

end

3、实例1:输出不同相位下的sin(x)

%Example 1:

%

clc;

x=1:0.1:20;

phase=[0,0.5*pi,pi,1.5*pi];

Color1=[55,130,189];

Color2=[235,25,28];

ResultColor=Transition_Two_Color(Color1,Color2,length(phase));%Get the transition color

figure;

subplot(1,2,1)%sin

for iPhase=1:length(phase)

    y=sin(x+phase(iPhase));

    plot(x,y,'linewidth',1.5,'color',ResultColor(iPhase,:)/256);%[R,G,B] in plot.m should convert to range 0 to 1

    hold on;

end

legend({'phase=0','phase=0.5*pi','phase=pi','phase=1.5*pi'},'FontName','Times New Roman','Fontsize',16);

set(gca,'linewidth',1.5,'FontName','Times New Roman','FontSize',16);

xlabel('x');ylabel('sin(x+Phase)');

title('sin(x+Phase)');

实例1结果如下图所示。

MATLAB如何在两个颜色间产生任意多个过渡色?

4、实例2:输出不同底数的指数函数

%Example 2:

clc;

x=-5:0.1:5;

BaseNum=[-2,-1,1,2];

Color1=[55,130,189];

Color2=[235,25,28];

ResultColor=Transition_Two_Color(Color1,Color2,length(BaseNum));

for iBaseNum=1:length(BaseNum)

    y=BaseNum(iBaseNum).^x;

    plot(x,y,'linewidth',1.5,'color',ResultColor(iBaseNum,:)/256);%[R,G,B] in plot.m should convert to range 0 to 1

    hold on;

end

set(gca,'linewidth',1.5,'FontName','Times New Roman','FontSize',16);

legend({'BaseNum=-2','BaseNum=-1','BaseNum=1','BaseNum=2'},'FontName','Times New Roman','Fontsize',16);

xlabel('x');ylabel('BaseNum\^x');

title('BaseNum\^x');

实例2结果如下图所示。

MATLAB如何在两个颜色间产生任意多个过渡色?

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢