TweetFollow Us on Twitter

Nov 98 Getting Started

Volume Number: 14 (1998)
Issue Number: 11
Column Tag: Getting Started

Color QuickDraw Basics

by Dave Mark and Dan Parks Sydow

How a Mac program handles color

Last month's column introduced black and white animation. Next month's column looks at color animation. Before we make the transition from monochrome to color, we need to gain an understanding of Color QuickDraw - the part of the Macintosh Toolbox that allows a programmer to bring color into a program.

When creating a program, great effort can be spent in setting up data structures, or developing algorithms, or performing some other behind-the-scenes chore. So often times a programmer's hard work doesn't seem to really do much - a long programming session may result in a lot of code being written, but very little of it displays anything on screen. That's what makes working with color one of the most enjoyable parts of programming. Not only do you get to see the results of your efforts, you get to see them in brilliant, splendid color!

You'll have a little fun this month learning about programming in color - but we can't let you have too much fun. With that in mind, this month's article also covers the topics of multiple monitors and monitor pixel depth. Although you may only have one monitor connected to your Mac, and although you may know the number of colors your monitor is displaying, can you say the same for every one of the users of your soon-to-be-written, best-selling, color Mac program? Here you'll see how your program can easily account for the many possible monitor and color level combinations on the systems of Mac users.

About Color QuickDraw

The original version of QuickDraw shipped with the very first Macs, and supported the display of only black-and-white drawing on the built-in screen. To keep track of the color of any one screen pixel required just a single bit (with the bit's two states representing black and white). The original QuickDraw supported a pixel depth of 1 - one bit dedicated to one pixel. Ever since the introduction of the Macintosh II, all Macs have shipped with a new version of QuickDraw known as Color QuickDraw. Color QuickDraw started as an 8-bit technology. Dedicating 8 bits to a pixel allowed for the support of 256 colors, and gave this version of QuickDraw a pixel depth of 8. Color QuickDraw then migrated to a 32-bit technology. This pixel depth of 32 could supporting millions of colors.

It's been quite a while since Apple shipped a Mac that didn't support color, so in all likelihood the user of your color program will be able to view it as you intended it to be seen. Still, your program should verify that the host machine does in fact have a version of Color QuickDraw. You'll do this for the sake of those few who are still using monochrome Macs. If your program attempts to use Color QuickDraw Toolbox routines on such a computer, it will crash that machine. Fortunately the Gestalt() Toolbox function makes it easy to test for the presence of Color QuickDraw.

If you aren't familiar with Gestalt(), you should get acquainted with it. This routine is a powerful tool that can be used to find out all sorts of things about the hardware and software of the Mac that a program is currently running on. In general, if you want to take advantage of a feature of the Macintosh that is not necessarily available on every Mac, you'll want to call Gestalt() to make sure the feature is present. Here's the prototype for Gestalt():

OSErr Gestalt( OSType selector, long *response );

Gestalt() takes two parameters. The first, selector, allows you to tell Gestalt() what part of the hardware or software you are interested in. You can use Gestalt() to find out how much RAM is on the current Mac, what version of the operating system is installed, what processor is in the Mac, whether the machine supports Color QuickDraw, and much, much more.

After executing, Gestalt() places the requested information in the second parameter, response. The type of information in response depends on the selector used. There's an Apple-defined selector constant for just about every imaginable Mac feature. Here we'll look at just the gestaltQuickdrawVersion selector. You can check the Gestalt Manager chapter of Inside Macintosh: Operating System Utilities, or peruse the Gestalt.h universal interface header file, to learn more about Gestalt() and its various selectors and responses.

To check for the presence of Color QuickDraw, begin by calling Gestalt() with a selector of gestaltQuickdrawVersion:

long   response;
OSErr  err;

err = Gestalt( gestaltQuickdrawVersion, &response );

Now compare the returned value in response to one of the pertinent Apple-defined response constants. For a selector of gestaltQuickdrawVersion there are five possible values Gestalt() might return:

gestaltOriginalQD        = 0x0000,         /* original 1-bit QD */
gestalt8BitQD            = 0x0100,         /* 8-bit color QD */
gestalt32BitQD           = 0x0200,         /* 32-bit color QD */
gestalt32BitQD11         = 0x0201,         /* 32-bit color QDv1.1 */
gestalt32BitQD12         = 0x0220,         /* 32-bit color QDv1.2 */
gestalt32BitQD13         = 0x0230          /* 32-bit color QDv1.3 */

To check for a particular version of Color QuickDraw, test the response as such:

if ( response == gestalt32BitQD )

It's more likely that you're program will simply want to know if the user's machine supports color - any color. To do that, see if the response is greater than the constant representing the original, monochrome version of QuickDraw. Here's the test we'll be using in this month's example:

if ( response > gestaltOriginalQD )

If the above test fails, exit the program or, better yet, call an error-handling routine to alert the user of the incompatibility problem.

Monitors and Color Levels

If you connect a second monitor to your Macintosh, it may or may not have the same pixel depth as the first monitor. That is, one monitor (or the graphics card controlling the monitor) may be capable of displaying more colors than the other monitor. Even if the two monitors are capable of displaying the same number of colors, at any given time they may not be doing that - the user may have limited the pixel depth of a monitor using the Monitors & Sound control panel. Because of this, the Mac needs a means of being able to know the state of each monitor, or graphics device.

Color QuickDraw represents each graphics device attached to a Mac, whether a display device or an offscreen color device (offscreen situations will be discussed in next month's article), using a gDevice data structure. Toolbox routines like GetDeviceList(), GetNextDevice(), and GetMainDevice() work with a gDevice data structure. To obtain a handle to the first device in a gDevice list, call GetDeviceList():

GDHandle      curDevice;
   
curDevice = GetDeviceList();

To find out which device is currently set to display the most colors, cycle through the list of devices. To do that, call GetNextDevice() within a loop. Before getting the next device from the gDevice list, check the pixel depth of the current device by calling the application-defined routine GetDeviceDepth().

short      curDepth;
while ( curDevice != NULL )
{
   curDepth = GetDeviceDepth( curDevice );
      
   curDevice = GetNextDevice( curDevice );
}

As you'll see in the code walk-though, there's a little bit more to it then what's shown above. In particular, you'll need to see how the application-defined GetDeviceDepth() is implemented. Also, when we encounter the device that has the greatest color depth, we'll want to save that information in the body of the above loop.

The RGB Color Model

Color QuickDraw represents colors using the RGB model. RGB stands for red, green, and blue - the three colors that combine to make up a single RGB color. The RGB model is based on the RGBColor data structure:

struct RGBColor
{
   unsigned short   red;
   unsigned short   green;
   unsigned short   blue;
};

Each component of an RGBColor can take on a value from 0 to 65535. The lower the value, the less intense the contribution of that one color to the overall, combined color. For instance, if red is 65535 and blue and green are both 0, the resulting color is bright red. As a second example, if the green component has a value of 0, and the red and blue components each have a value of 65535, then the resulting color will be an intense violet - a color rich in red and blue, but lacking any green. The extremes of the color spectrum are black and white. If red, green, and blue are each 0, the RGBColor represents black - the lack of any color in each component results in this dimmest of colors. If all three components are each set to 65535, the RGBColor represents white - the maximum intensity of each component creates this, the brightest of colors. As an aside, "colors" is used loosely in the previous two sentences. Black and white aren't truely colors: black is the absense of color, while white is the mixture of all visible wavelengths (so white is the combination of all colors).

We'll work with the RGB model throughout this program. Be aware that Color QuickDraw does support other color models, such as HSV (which is hue, saturation and brightness) and CMY (which is cyan, magenta, yellow) and provides routines that convert colors between each model.

To take advantage of the Color QuickDraw routines, you'll want to replace your use of WindowRecords with CWindowRecords. CWindowRecords are similar to WindowRecords, with a CGrafPort replacing the traditional GrafPort. Even with these changes, you can pass a pointer to a CWindowRecord to all the routines that usually take a WindowPtr. In this article's program, the only noticeable instance of working with color windows is in the creation of a window, where a call to GetNewCWindow() replaces the call we've used in the past - GetNewWindow().

ColorMondrian

This month's program, ColorMondrian, checks to see which monitor is capable of displaying the most colors and then opens a window on that monitor. If the user's Mac has only one monitor, then of course ColorMondrian knows to display the window on it. After the window is resized to match the size of the monitor's screen, the program draws randomly generated ovals, in randomly selected colors. ColorMondrian works just fine on a system that has a grayscale monitor - in Color QuickDraw shades of gray count as colors too! The shapes are continuously drawn until the user quits the program. Figure 1 shows a part of the_ColorMondrian window as shapes are being drawn to it.

Figure 1. The ColorMondrian window.

Creating the ColorMondrian Resources

To get started, move into your CodeWarrior development folder and create a folder named ColorMondrian. Launch ResEdit and create a new resource file named ColorMondrian.rsrc inside the ColorMondrian folder. Figure 2 shows the five types of resources used by ColorMondrian - you'll notice that they're all types with which you're familiar.

Figure 2. The MENU resources.

Figure 2 also shows the two particular MENU resources the program needs. Of course your own real-world color application will have more MENU resources, including one for the standard Edit menu and one for each application-defined menu.

ColorMondrian uses one ALRT and one DITL resource - they're shown in Figure 3. Both are used to support the error-handling alert displayed by the program's DoError() routine (a routine touched on in the ColorMondrian walk-through, and discussed at length two articles ago in the Getting Started column on Apple Events).

Figure 3. The resources needed to implement error-handling.

The only other resource needed is a WIND that will be used to hold the randomly drawn shapes. The size of the WIND isn't critical - we'll be resizing the window from within the source code. Since the window will be fixed on the screen, the type of WIND isn't of great importance either.

That's it for the ColorMondrian.rsrc file. Now quit ResEdit, making sure to first save your changes.

Creating the ColorMondrian Project

Launch CodeWarrior and create a new project based on the MacOS:C_C++:MacOS Toolbox:MacOS Toolbox Multi-Target stationary. You've already created the ColorMondrian project folder, so uncheck the Create Folder check box. Name the project ColorMondrian.mcp and specify that the project be placed in the ColorMondrian folder.

In the newly created project window you can go ahead and remove the SillyBalls.c and SillyBalls.rsrc files. Then add the ColorMondrian.rsrc file. The ColorMondrian project doesn't use any of the standard ANSI libraries, so you'll be safe in removing the ANSI Libraries folder.

Now choose New from the File menu to create a new, empty source code window. Save it with the name ColorMondrian.c. Add this new, empty file to the project by choosing Add Window from the Project menu. You'll find the complete source code listing for ColorMondrian in the source code walk-through. You can type it into the ColorMondrian.c file as you read the walk-through, or you can save yourself some effort and download the whole ColorMondrian project from MacTech's ftp site at ftp://ftp.mactech.com/src/mactech/volume14_1998/14.11.sit.

Walking Through the Source Code

As in past projects, ColorMondrian starts off with some constant definitions.

/********************* constants *********************/

#define kMBARResID               128
#define kALRTResID               128
#define kWINDResID               128

#define kSleep                   7
#define kMoveToFront             (WindowPtr)-1L
#define kWindowMargin            15

#define kRandomUpperLimit        32768

#define kDelaySixtiethSeconds    2

#define mApple                   128
#define iAbout                   1

#define mFile                    129
#define iQuit                    1

These are followed by ColorMondrian's one global variable:

/****************** global variables *****************/

Boolean      gDone;

Next come the program's function prototypes:

/********************* functions *********************/

void         ToolBoxInit( void );
Boolean      HasColorQD( void );
void         MenuBarInit( void );
GDHandle     GetDeepestDevice( void );
short        GetDeviceDepth( GDHandle device );
void         CreateWindow( GDHandle device );
void         EventLoop( void );
void         DrawRandomOval( void );
void         RandomColor( RGBColor *colorPtr );
void         RandomRect( Rect *rectPtr );
short        Randomize( short range );
void         DoEvent( EventRecord *eventPtr );
void         HandleMouseDown( EventRecord *eventPtr );
void         HandleMenuChoice( long menuChoice );
void         HandleAppleChoice( short item );
void         HandleFileChoice( short item );
void         DoError( Str255 errorString );

The main() function starts off with the declaration of a variable that's to be used to keep track to the deepest device - the graphic device currently set to display the most colors.

/************************ main ***********************/

void   main( void )
{
   GDHandle   deepestDevice;

Next, it's the familiar call to the Toolbox initialize function ToolBoxInit(). After that we call HasColorQD() (discussed next) to check for the presence of a version of Color QuickDraw. If the user's Mac doesn't support color, we invoke our own error-handling routine to inform the user of the reason the program is exiting.

   ToolBoxInit();
   
   if ( ! HasColorQD() )
      DoError( "\pThis Mac doesn't support Color QuickDraw!" );

A call to MenuBarInit() (another familiar routine, and one shown ahead) loads the menu-related resources and displays the menu bar. Then the local variable deepestDevice is set to reference the - you guessed it - device with the deepest pixel depth. This variable is passed to CreateWindow() so that the program's one window will be opened on the desired monitor. Both GetDeepestDevice() and CreateWindow() are described a bit down the way. A call to our now standard EventLoop() function wraps up main().

   MenuBarInit();
   
   deepestDevice = GetDeepestDevice();
   CreateWindow( deepestDevice );
   
   EventLoop();
}

ToolBoxInit() is, as you've certainly surmised, the same as in the past:

/******************** ToolBoxInit ********************/

void   ToolBoxInit( void )
{
   InitGraf( &qd.thePort );
   InitFonts();
   InitWindows();
   InitMenus();
   TEInit();
   InitDialogs( 0L );
   InitCursor();
}

HasColorQD() holds the call to Gestalt() that tells whether Color QuickDraw is installed. The gestaltQuickdrawVersion selector retrieves a value that is compared to the Apple-defined constant gestaltOriginalQD. Before examining response, HasColorQD() makes sure that the call to Gestalt() itself was successful (irrespective of the value now held in response). If we're error-free, it's on to the determination of whether Color QuickDraw is present. If response is greater than gestaltOriginalQD, the host machine has a version of QuickDraw other than the original version (and hence a Color QuickDraw version), the comparison test passes, and HasColorQD() returns a value of true to tell the caller (main()) to carry on with the program. If response is equal to gestaltOriginalQD, ColorMondrian is running on a monochrome Mac and needs to terminate.

/********************* HasColorQD ********************/

Boolean   HasColorQD( void )
{
   long      response;
   OSErr   err;

   err = Gestalt( gestaltQuickdrawVersion, &response );

   if ( err != noErr )
      DoError( "\pError calling Gestalt()" );

   if ( response > gestaltOriginalQD )
      return( true );
   else
      return( false );   
}

MenuBarInit() introduces no new code:

/******************** MenuBarInit ********************/

void   MenuBarInit( void )
{
   Handle            menuBar;
   MenuHandle      menu;
   
   menuBar = GetNewMBar( kMBARResID );
   SetMenuBar( menuBar );

   menu = GetMenuHandle( mApple );
   AppendResMenu( menu, 'DRVR' );
   
   DrawMenuBar();
}

GetDeepestDevice() steps through the device list, calling the application-defined GetDeviceDepth() function (described next) to determine the device with the deepest pixel depth. Most of the code in GetDeepestDevice() was described earlier in this article. Here you see the addition of code that keeps track of the maximum color depth and the device on which this maximum is found. We need to carry out the loop until all devices are checked - the last device in the list may be the one with the maximum depth. Each pass through the loop compares what is so far the maximum depth with the depth of the device currently being checked. When the entire device list has been checked, the device with the deepest depth is returned to the caller (which is main()).

/***************** GetDeepestDevice ******************/

GDHandle   GetDeepestDevice( void )
{
   GDHandle   curDevice, maxDevice = NULL;
   short      curDepth, maxDepth = 0;
   
   curDevice = GetDeviceList();
   
   while ( curDevice != NULL )
   {
      curDepth = GetDeviceDepth( curDevice );
      
      if ( curDepth > maxDepth )
      {
         maxDepth = curDepth;
         maxDevice = curDevice;
      }

      curDevice = GetNextDevice( curDevice );
   }
   
   return( maxDevice );
}

GetDeviceDepth() starts by retrieving a handle to the device's PixMap from the GDevice structure. A PixMap is a color version of a BitMap. The BitMap data structure was discussed in last month's article - the PixMap data structure will be described in next month's column (if you're impatient check out the Color QuickDraw chapter of Inside Macintosh: Imaging With QuickDraw). The pixelSize field holds the depth of this PixMap. That reveals the device's depth, so that's what's returned to the caller (the GetDeepestDevice() function).

/****************** GetDeviceDepth *******************/

short   GetDeviceDepth( GDHandle device )
{
   PixMapHandle   screenPixMapH;
   
   screenPixMapH = (**device).gdPMap;
   
   return( (**screenPixMapH).pixelSize );
}

CreateWindow() creates a window on the specified device. Recall that main() invoked GetDeepestDevice() just before calling CreateWindow(). Doing so enabled main() to pass CreateWindow() the device that is to be the recipient of the new window:

/******************* CreateWindow ********************/

void   CreateWindow( GDHandle device )
{
   WindowPtr   window;
   Rect        wBounds;
   long        windowWidth, windowHeight;

The handle stored in device must be dereferenced twice to get to the GDevice structure. The gdRect field is a Rect containing the device's bounding rectangle.

   wBounds = (**device).gdRect;

GetMainDevice() returns a handle to the device containing the menu bar. If the device that is to receive the new window happens to be the main device, we need to take the height of the menu bar into account when calculating the window's size and placement. The Toolbox function GetMBarHeight() returns the height of the menu bar in pixels.

   if ( device == GetMainDevice() )
      wBounds.top += GetMBarHeight();

Purely for aesthetic reasons we make the window a little smaller then the screen. A call to InsetRect() handles that task.

   InsetRect( &wBounds, kWindowMargin, kWindowMargin );

Now we call GetNewCWindow() to create a new CWindowRecord, as opposed to the WindowRecord that would result from a call to GetNewWindow().

   window = GetNewCWindow( kWINDResID, nil, kMoveToFront );

The window is based on a WIND resource. At the time the WIND was created there was obviously no way of knowing the size of the monitor that would eventually be displaying the window. So now, in our code, we need to adjust the window's size and location before showing it. We base the calculations on the boundaries of the wBounds rectangle, which holds the display area of the graphics device (less the menu bar height, if relevant). Calls to the Toolbox functions SizeWindow() and MoveWindow() take care of the window manipulations.

   windowWidth = wBounds.right - wBounds.left;
   windowHeight = wBounds.bottom - wBounds.top;
   
   SizeWindow( window, windowWidth, windowHeight, true );
   MoveWindow( window, wBounds.left, wBounds.top, true );
   
   ShowWindow( window );
   SetPort( window );
}

EventLoop() includes the same code as previous versions, but it also adds a few new lines. The first addition is a call to the Toolbox function GetDateTime(). This call is made to initialize the randSeed field of the global data structure qd.

If you've made use of any of the five standard patterns (as in qd.ltGray and qd.black) or if you've accessed the map of the screen (qd.screenBits), you're familiar with the system-defined qd variable. The QDGlobals data structure of which qd is based on includes a randSeed member that serves as a seed for a random number generator. A computer's random number generator isn't truly random - given the same seed, or initial value, from which to generate random numbers, it will always produce the same sequence of numbers. This behavior won't matter during one running of a program - the seed is only used once to "kick off" the generator, and after that the generated numbers then seem to be random. Using the same seed will matter during subsequent running of the program - the same sequence of supposedly random numbers will appear during each running of the program. This repetitive sequence of random numbers can be avoided by choosing a different seed value during each running of a program. The GetDateTime() routine is generally used to return a long value that specifies the number of seconds that have elapsed from midnight January 1st 1904 until the time of the call to GetDateTime(). So each call to GetDateTime() is guaranteed to produce a unique value (provided the calls are made greater than one second apart!). We'll take advantage of that fact to use GetDateTime() not as a means of determining the current date, but instead to set the qd data member randSeed to a value never before used by the ColorMondrian program.

/********************* EventLoop *********************/

void   EventLoop( void )
{      
   EventRecord      event;
   unsigned long   finalTicks;   
   
   GetDateTime( (unsigned long *)(&qd.randSeed) );

Now, on to the loop that repeatedly calls WaitNextEvent() and DoEvent() to retrieve and handle a single event. In this loop we've added a delay and a call to the application-defined DrawRandomOval() function. The purpose of DrawRandomOval() (discussed next) is obvious - it draws a single, randomly sized and placed oval. The delay is included to slow down the drawing - without it the program really flies! Delay() is a Toolbox function that pauses a program. The first parameter is the number of sixtieths of a second to delay (pass 30 to delay a half second, 60 to delay a full second, and so forth). The second parameter is a value filled in by the Delay() function. We ignore this returned value - it represents the number of sixtieths of a second that have elapsed since the user's Mac was started up. You can omit the delay by commenting out the call to Delay(). You can increase the delay by upping the value of the application-defined constant kDelaySixtiethSeconds.

   gDone = false;
   while ( gDone == false )
   {
      if ( WaitNextEvent( everyEvent, &event, kSleep, nil ) )
         DoEvent( &event );
      
      Delay( kDelaySixtiethSeconds, &finalTicks );   
      DrawRandomOval();
   }
}

DrawRandomOval() generates a random color, makes that color the current foreground color, generates random boundaries for an oval, and then draws that oval in the foreground color. RandomColor() and RandomRect() are application-defined routines that are described next.

/******************* DrawRandomOval ******************/

void   DrawRandomOval( void )
{
   Rect         randomRect;
   RGBColor   color;
   
   RandomColor( &color );
   RGBForeColor( &color );
   RandomRect( &randomRect );
   PaintOval( &randomRect );
}

DrawRandomOval() calls RandomColor() to generate an RGBColor. RandomColor() comes up with this RGBColor by randomly generating values for red, green, and blue that range from 0 to 65534. A call to the Toolbox function Random() generates a value in the range of -32767 to 32767. Adding 32767 to the number produced by Random() results in a value in the range used to specify each component of an RGBColor.

/********************* RandomColor *******************/

void   RandomColor( RGBColor *colorPtr )
{
   colorPtr->red = Random() + 32767;
   colorPtr->blue = Random() + 32767;
   colorPtr->green = Random() + 32767;
}

DrawRandomOval() calls RandomRect() to generate a random rectangle. The size of this rectangle is dependent on the size of the frontmost (and in this program, the only) window. It will be within this rectangle that DrawRandomOval() inscribes an oval.

/******************** RandomRect ********************/

void   RandomRect( Rect *rectPtr )
{
   WindowPtr   window;
   short         windowWidth;
   short         windowHeight;
   
   window = FrontWindow();
   
   windowWidth = window->portRect.right - 
                 window->portRect.left;
   windowHeight = window->portRect.bottom - 
                  window->portRect.top;

   rectPtr->left = Randomize( windowWidth );
   rectPtr->right = Randomize( windowWidth );
   rectPtr->top = Randomize( windowHeight );
   rectPtr->bottom = Randomize( windowHeight );
}

RandomRect() relies on Randomize() to do the work of generating a number from 0 to the specified upper limit. Randomize() begins by calling the Toolbox function Random() to generate a number in the range of -32767 to 32767. If the value is negative, we simply multiply it by -1 to make it positive. Multiplying by the range (which is either the width or height of the window) and then dividing by kRandomUpperLimit (defined to be 32767) results in a value that is always greater than or equal to 0 and and always less than or equal to the width or height of the window.

/******************** Randomize **********************/

short   Randomize( short range )
{
   long      randomNumber;
   
   randomNumber = Random();
   
   if ( randomNumber < 0 )
      randomNumber *= -1;
   
   return( (randomNumber * range) / kRandomUpperLimit );
}

That's the last you'll need to hear from us for the remainder of the code walk-through. The DoEvent(), HandleMouseDown(), HandleMenuChoice(), HandleAppleChoice(), HandleFileChoice(), and DoError() functions are all similar to versions introduced and explained in recent columns.

/*********************** DoEvent *********************/

void   DoEvent( EventRecord *eventPtr )
{
   char   theChar;
   
   switch ( eventPtr->what )
   {
      case mouseDown: 
         HandleMouseDown( eventPtr );
         break;
      case keyDown:
      case autoKey:
         theChar = eventPtr->message & charCodeMask;
         if ( (eventPtr->modifiers & cmdKey) != 0 ) 
            HandleMenuChoice( MenuKey( theChar ) );
         break;
   }
}

/****************** HandleMouseDown ******************/

void   HandleMouseDown( EventRecord *eventPtr )
{
   WindowPtr   window;
   short       thePart;
   long        menuChoice;
   
   thePart = FindWindow( eventPtr->where, &window );
   
   switch ( thePart )
   {
      case inMenuBar:
         menuChoice = MenuSelect( eventPtr->where );
         HandleMenuChoice( menuChoice );
         break;
      case inSysWindow : 
         SystemClick( eventPtr, window );
         break;
   }
}

/***************** HandleMenuChoice ******************/

void   HandleMenuChoice( long menuChoice )
{
   short   menu;
   short   item;
   
   if ( menuChoice != 0 )
   {
      menu = HiWord( menuChoice );
      item = LoWord( menuChoice );
      
      switch ( menu )
      {
         case mApple:
            HandleAppleChoice( item );
            break;
         case mFile:
            HandleFileChoice( item );
            break;
      }
      HiliteMenu( 0 );
   }
}

/***************** HandleAppleChoice *****************/

void   HandleAppleChoice( short item )
{
   MenuHandle   appleMenu;
   Str255         accName;
   short         accNumber;
   
   switch ( item )
   {
      case iAbout:
         SysBeep( 10 );
         break;
      default:
         appleMenu = GetMenuHandle( mApple );
         GetMenuItemText( appleMenu, item, accName );
         accNumber = OpenDeskAcc( accName );
         break;
   }
}

/***************** HandleFileChoice ******************/

void   HandleFileChoice( short item )
{
   switch ( item )
   {
      case iQuit :
         gDone = true;
         break;
   }
}

/*********************** DoError *********************/

void   DoError( Str255 errorString )
{
   ParamText( errorString, "\p", "\p", "\p" );
   
   StopAlert( kALRTResID, nil );
   
   ExitToShell();
}

Running ColorMondrian

Run ColorMondrian by selecting Run from the Project menu. Once the code compiles, a window appears and begins to get filled with randomly colored, randomly placed, ovals. Make sure to choose Quit from the File menu to exit the program before hypnosis sets in!

Till Next Month...

There's a lot to learn about Color QuickDraw - hopefully, this column gave you a good foothold. You can continue learning about color programming by modifying the ColorMondrian code. If you want to experiment with QuickDraw shapes other than ovals, modify the DrawRandomOval() routine. Replace that function's call to PaintOval() with a call to your own application-defined function that randomly selects one of several shapes to draw. You can read up on shape-drawing in the QuickDraw Drawing chapter of Inside Macintosh: Imaging With QuickDraw.

To learn more about drawing in color, plan to spend some time in the Color QuickDraw chapter of Imaging With QuickDraw. In that chapter you'll find plenty of information on a variety of topics we've touched on here, including the Gestalt() function, RGB colors, color graphics ports, the setting of the foreground and background colors, and more.

After reading last month's column on monochrome animation and this month's column on Color QuickDraw, you're all set for color animation. That's coming next month. If you can't stand the suspense, go ahead and get a jump start on the topic by reading up on pixel maps and the PixMap data type in the Color QuickDraw chapter of Imaging With QuickDraw and on offscreen graphics worlds and the GWorld data type in the Offscreen Graphics Worlds chapter of that same book. We'll be back next month, in living color, to morph the monochrome BitMapper program into the color animation PixMapper program. See you then...

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.