将 css 颜色转换为 16 位 rgb



我正在尝试将像129a8f这样的css十六进制颜色转换为适合choose color default color xxx的格式(在本例中为{4626, 39578, 36751})。我有可以解决问题的红宝石代码

if m = input.match('([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})') then
  clr = "{#{m[1].hex*257}, #{m[2].hex*257}, #{m[3].hex*257}}"

现在我在AppleScript中需要相同的功能(我不知道;)。有什么指示吗?

您可以在

AppleScript脚本中使用ruby

set x to text returned of (display dialog "Type a css hex color." default answer "129a8f")
set xx to do shell script "/usr/bin/env ruby -e  'x="" & x & ""; if m= x.match("([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})") then puts "{#{m[1].hex*257}, #{m[2].hex*257}, #{m[3].hex*257}}"; end' "
if xx is "" then
    display alert x & " is not a valid css hex color" buttons {"OK"} cancel button "OK"
else
    set xxx to run script xx -- convert ruby string to AppleScript list
    set newColor to choose color default color xxx
end if

--

或者没有 ruby 的 AppleScript 脚本

property hexChrs : "0123456789abcdef"
set x to text returned of (display dialog "Type a css hex color." default answer "129a8f")
set xxx to my cssHexColor_To_RGBColor(x)
set newColor to choose color default color xxx
on cssHexColor_To_RGBColor(h) -- convert 
    if (count h) < 6 then my badColor(h)
    set astid to text item delimiters
    set rgbColor to {}
    try
        repeat with i from 1 to 6 by 2
            set end of rgbColor to ((my getHexVal(text i of h)) * 16 + (my getHexVal(text (i + 1) of h))) * 257
        end repeat
    end try
    set text item delimiters to astid
    if (count rgbColor) < 3 then my badColor(h)
    return rgbColor
end cssHexColor_To_RGBColor
on getHexVal(c)
    if c is not in hexChrs then error
    set text item delimiters to c
    return (count text item 1 of hexChrs)
end getHexVal
on badColor(n)
    display alert n & " is not a valid css hex color" buttons {"OK"} cancel button "OK"
end badColor

最新更新