[英]Function that takes a hex-color and returns a named vector with the values of the RGB and possibly alpha channels
例如,function 應該像這樣工作:
# colors with no transparency
hex_values("#435690")
## red green blue
## "43" "56" "90"
如果提供的十六進制顏色有一個 alpha 通道,那么 function 應該像這樣工作:
# colors with transparency
hex_values("#435690FF")
## red green blue alpha
## "43" "56" "90" "FF"
我正在使用正則表達式和 for 循環來編寫我的 function,但仍然遇到很多問題。
任何建議/幫助表示贊賞!
您可以使用col2rgb()
並轉置結果:
t(col2rgb("#435690FF", alpha = TRUE))
red green blue alpha
[1,] 67 86 144 255
或者正如 r2evans 指出的那樣,要恢復為十六進制值,請將其包裝在as.hexmode()
中。
t(as.hexmode(col2rgb("#435690FF", alpha = TRUE)))
red green blue alpha
[1,] "43" "56" "90" "ff"
要將注釋合並到 function 中:
hex_values <- function(x) {
clr <- ifelse(startsWith(x, "#"), x, paste0("#", x))
t(toupper(as.hexmode(col2rgb(clr, alpha = TRUE))))
}
hex_values(colorRampPalette(c("red", "blue"))(5))
red green blue alpha
[1,] "FF" "00" "00" "FF"
[2,] "BF" "00" "3F" "FF"
[3,] "7F" "00" "7F" "FF"
[4,] "3F" "00" "BF" "FF"
[5,] "00" "00" "FF" "FF"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.