Documentation Archive

Developer

Mac Automation Scripting Guide

Prompting for a Color

Use the Standard Additions scripting addition’s choose color command to ask the user to select a color from a color picker dialog like the one shown in Figure 29-1. The command accepts an optional default color parameter, and produces an RGB color value as its result. Listing 29-1 and Listing 29-2 display a color picker, create a TextEdit document containing some text, and apply the chosen color to the text.

Figure 29-1A color picker dialog image: ../Art/colorpicker_2x.png

APPLESCRIPT

Open in Script Editor

Listing 29-1AppleScript: Adding colored text to a new TextEdit document
  1. set theColor to choose color default color {0, 65535, 0}
  2. --> Result: {256, 40421, 398}
  3. tell application "TextEdit"
  4. set theDocument to make new document
  5. set text of document 1 to "Colored Text"
  6. set color of text of document 1 to theColor
  7. end tell

JAVASCRIPT

Open in Script Editor

Listing 29-2JavaScript: Adding colored text to a new TextEdit document
  1. var app = Application.currentApplication()
  2. app.includeStandardAdditions = true
  3. var color = app.chooseColor({defaultColor: [0, 1, 0]})
  4. // Result: [0.003753719385713339, 0.7206835746765137, 0.005828946363180876]
  5. color = [Math.trunc(color[0] * 65535), Math.trunc(color[1] * 65535), Math.trunc(color[2] * 65535)]
  6. var textedit = Application("TextEdit")
  7. var document = textedit.make({new: "document"})
  8. document.text = "Colored Text"
  9. document.text.color = [256, 40421, 398]