我正在使用colors.jl包并具有我需要转换为十六进制字符串三元组值的RGB值。最好的方法是什么?在colors.jl中找不到转换函数
谢谢
你可以定义一个自定义的struct
,它可以从AbstractRGB
构造而且具有适当的show
重载,如
import Base: show
using ColorTypes
struct RGBPacked
r::UInt8
g::UInt8
b::UInt8
function (::Type{RGBPacked})(c::AbstractRGB)
colvec = (red(c), green(c), blue(c))
temp = map(UInt8, map(x->floor(255*x), colvec))
new(temp[1], temp[2], temp[3])
end
end
function show(io::IO, r::RGBPacked)
print(io, "#$(hex(r.r))$(hex(r.g))$(hex(r.b))")
end
然后,您可以使用自定义数据类型
c1 = RGB(1.,0.5,0.7)
c2 = RGBPacked(c1)
打印
Main> c1 = RGB(1.,0.5,0.7)
RGB{Float64}(1.0,0.5,0.7)
Main> c2 = RGBPacked(c1)
#ff7fb2