Colordepth-independent color references

Date:    Thu, 27 Feb 1997 17:34:04 -0800
From:    Mitchell Yawitz <yawitz@mlodge.com>
Subject: Colordepth-independent color references
In going through some recent (a couple of weeks or so) back digests, I noticed the question of color references when moving between 8-, 16-, and 24-bit displays coming up again.

(Summary: color properties for 8-bit displays are indices into a color palette, range [0..255], while references in 16- and 24-bit displays are essentially packed RGB values. For example, pure WHITE in the Mac palette has the value 0, while in 16-bit it has the value 32767.)
Since I just needed to deal with this issue in a project I'm building, I thought I'd post the solution I use (which had already been suggested by a number of folks on the list).


--- First, define a text field and name it. (Example: "SystemMac")

--- Then, run the following handler, with the field name as an argument

  on buildIndexColorChars fieldRef
    -- NOTE: This is an author-time Handler
    -- Build a field of 256 chars (specified by fieldRef), and set the color
    -- of each char to an 8-bit color index (based on the char position).
    -- The colors of the chars will be based on the currently active palette.
    -- TIP: Name the field based on the built-in Director palette symbols
    --      (systemMac, rainbow, etc.)
    --
    -- First, save current color depth, and set screen to 8-bit color
    put the colorDepth into savedDepth
    set the colorDepth to 8
    -- build the chars
    put EMPTY into tempStr
    repeat with i = 0 to 255
      put "x" after tempstr
    end repeat
    put tempStr into field fieldRef
    -- Set the colors
    repeat with i = 0 to 255
      set the foreColor of char (i+1) of field fieldRef to i
    end repeat
    -- Restore color depth
    set the colorDepth to savedDepth
  end buildIndexColorChars

--- Note that this is done just once; the resulting field can then be
--- saved and pasted into other projects.

--- Now, to reference a color based on its original palette position,
--- use the following handler:

  on indexColor fieldRef, colorIndex
    -- Get the value of the (fore)color of char colorIndex, from field fieldRef
    -- (which should have been built using buildIndexColorChars, above).
    return the foreColor of char colorIndex+1 of field fieldRef
  end indexColor

--- (Note: if the fields are named based on Director's palette symbols,
---  as hinted at in the paletteRef entry in the Lingo Dictionary, then
---  you can turn symbol references into arguments to indexColor()
---  using the string() function.)

--- For example:
  put indexColor("SystemMac", 0)
  -- 0
  --(change display to 16-bit color)
  put indexColor("SystemMac", 0)
  -- 32767