2014-02-09 172 views
0

我試圖將css十六進制顏色(如129a8f)轉換爲適合於choose color default color xxx(在這種情況下爲{4626, 39578, 36751})的格式。我有ruby代碼,這是伎倆將css顏色轉換爲16位rgb

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中的相同(我不知道;)。任何指針?

+0

的ALGO很簡單 - 打破十六進制字符串到雙每2 - '129a8f'給出表示'12 9A 8f' R,G和B。將這些十六進制中的每一個轉換爲等效的整數將會給你所需的結果。現在你可以用你喜歡的任何語言來實現。 –

+0

@AshisKumarSahoo:謝謝,但我的問題是關於Applescript的具體問題。 – georg

回答

2

您可以在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 

-

或者沒有紅寶石AppleScript腳本

property hexChrs : "abcdef" 

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 
+0

完美,謝謝你。 – georg