# Matlab实现四种HSV色轮图绘制的示例代码

## 明度(V)渐变版

```% 生成网格
tList=linspace(0,2.*pi,300);
rList=linspace(0,1,100);
[theta,R]=meshgrid(tList,rList);

% 角度及半径转换为坐标
X=cos(theta+pi).*R;
Y=sin(theta).*R;
Z=zeros(size(X));

% 构造hsv网格并转换为rgb网格
hsvMesh=cat(3,theta./2./pi,ones(size(R)),R);
rgbMesh=hsv2rgb(hsvMesh);

% surf绘图
surf(X,Y,Z,"EdgeColor","none","CData",rgbMesh)
axis equal;axis([-1,1,-1,1]);
view(0,90);
```

## 饱和度(S)渐变版

```% 生成网格
tList=linspace(0,2.*pi,300);
rList=linspace(0,1,100);
[theta,R]=meshgrid(tList,rList);

% 角度及半径转换为坐标
X=cos(theta).*R;
Y=sin(theta).*R;
Z=zeros(size(X));

% 构造hsv网格并转换为rgb网格
hsvMesh=cat(3,theta./2./pi,R,ones(size(R)));
rgbMesh=hsv2rgb(hsvMesh);

% surf绘图
surf(X,Y,Z,"EdgeColor","none","CData",rgbMesh)
axis equal;axis([-1,1,-1,1]);
view(0,90);
```

## 明度饱和度不变花瓣版

```% 构造花瓣形状
t=(0:.1:(2.01/3*pi))+pi;
CX=cos(t)+1;
CY=sin(t);
[NCX,NCY]=rotateData(CX,CY,pi/6);
NCX=[NCX,NCX(end:-1:1)];
NCY=[NCY,-NCY(end:-1:1)];

% 循环绘图
hold on;
tt=linspace(0,2*pi,33);tt(end)=[];
for i=tt
[tNCX,tNCY]=rotateData(NCX,NCY,i);
fill(tNCX,tNCY,hsv2rgb([i/2/pi,1,1]),"FaceAlpha",0.2,...
"LineWidth",1.5,"EdgeColor",[1,1,1],"EdgeAlpha",0.5)
end
axis equal;axis([-1.8,1.8,-1.8,1.8]);

% 数据旋转角度
function [X,Y]=rotateData(X,Y,theta)
rotateMat=[cos(theta),-sin(theta);sin(theta),cos(theta)];
XY=rotateMat*[X;Y];
X=XY(1,:);Y=XY(2,:);
end
```

## HSV全空间

```% 线性划分
h=linspace(0,2*pi,31);h=h(1:26);
s=linspace(0,1,9);
v=linspace(0,1,11);

% 绘制上面
hold on;
[H,S]=meshgrid(h,s);
surf(S.*cos(H),S.*sin(H),H-H+1,hsv2rgb(cat(3,H/2/pi,S,H-H+1)));
% 绘制侧面
[H,V]=meshgrid(h,v);
surf(V.*cos(H),V.*sin(H),V,hsv2rgb(cat(3,H/2/pi,H-H+1,V)));
% 绘制两个截面
[S,V]=meshgrid(s,v);
surf(S.*V.*cos(h(1)),S.*V.*sin(h(1)),V,hsv2rgb(cat(3,S-S+h(1)/2/pi,S,V)));
surf(S.*V.*cos(h(end)),S.*V.*sin(h(end)),V,hsv2rgb(cat(3,S-S+h(end)/2/pi,S,V)));