Fortran For Fun之文字颜色显示

可以在字符的前端和后端添加一些特殊字符,使字符在终端的显示带有颜色。

color

以下color模块中定义了两个函数:

  • colorize(s,c)
    该函数输入一个字符串s和一个RGB数组c(3)=[r,g,b],其中 r,g,b在[0,5]之间。返回带有颜色的字符串。
  • color_map(v,r)
    该函数输入一个颜色相对位置v 在颜色范围r = [lbound, ubound]内,返回一个RGB数组, 该color_map属于 coolwarm 。

注意字符串只有在终端才会显示颜色,在文本编辑器中可能会出现乱码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
module color
implicit none
public :: colorize, color_map
private
contains
!=============================================================================
function colorize(s,c) result(o)
!< Bracket a string with text to change its color on a terminal
character(*),intent(in)::s !< String to colorize
integer,dimension(3),intent(in)::c ! c in [0,5]
!< Color to use in [r,g,b] format, where \(r,g,b \in [0,5]\)
character(:),allocatable::o
character(1),parameter::ESC = achar(27)
character(3),parameter::post = '[0m'
character(8) :: pre
write(pre,'(i0)') 36*c(1)+6*c(2)+c(3)+16
o = ESC//'[38;5;'//trim(adjustl(pre))//'m'//s//ESC//post
end function colorize
!=============================================================================
function color_map(v,r) result(c)
!< Return the color code for colorize based on the coolwarm color map
real,intent(in)::v
!! Value to map
real,dimension(2),intent(in)::r
!! Range over which to scale the colors
integer,dimension(3)::c
integer::s
if(v<sum(r)/2.0) then
s = nint((v-r(1))/(sum(r)/2.0-r(1))*5.0)
c = [s,s,5]
else
s = 5-nint((v-sum(r)/2.0)/(r(2)-sum(r)/2.0)*5.0)
c = [5,s,s]
end if
end function color_map
end module color

colorize

以下程序测试了colorize的颜色显示,对常用的几种颜色的RGB进行了定义。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
program learn_colorize
use color
implicit none
integer, parameter :: black(3) = [0,0,0],&
& white(3) = [5,5,5],&
& red(3) = [5,0,0],&
& green(3) = [0,5,0],&
& blue(3) = [0,0,5],&
& yello(3) = [5,5,0],&
& cyan(3) = [5,0,5],&
& purple(3)= [0,5,5]
print*, colorize('black',black)
print*, colorize('white',white)
print*, colorize('red',red)
print*, colorize('green',green)
print*, colorize('blue',blue)
print*, colorize('yello',yello)
print*, colorize('cyan',cyan)
print*, colorize('purple',purple)
end program learn_colorize

结果

colorize

color_map

以下程序将colormap用21个颜色进行显示

1
2
3
4
5
6
7
8
9
10
program learn_colormap
use color
implicit none
integer :: i
do i = 0,20
print*, colorize('corlormap',color_map(v=0.05*i,r=[0.,1.]))
enddo
end program learn_colormap

结果