TweetFollow Us on Twitter

Screen Savers in Cocoa

Volume Number: 20 (2004)
Issue Number: 6
Column Tag: Programming

Screen Savers in Cocoa

by Scott Knaster

One of the classic mantra-like goals for computer science over the past 20 years or so has been to "Make simple things simple, and complex things possible". Programming with Cocoa has a sometimes-complex learning curve, but once you've swerved through that curve, there are definitely a bunch of things that are much easier to accomplish than they were in the old pre-OS X world we knew and occasionally loved.

One of the classic mantra-like goals for computer science over the past 20 years or so has been to "Make simple things simple, and complex things possible". Programming with Cocoa has a sometimes-complex learning curve, but once you've swerved through that curve, there are definitely a bunch of things that are much easier to accomplish than they were in the old pre-OS X world we knew and occasionally loved. Writing a screen saver is a perfect example: it should be simple. Most typical OS 9 application programmers never dipped their toes into the slightly wacky world of screen savers, but with Cocoa in OS X, implementing a screen saver is well within everybody's grasp. In this month's column, we'll take a look at how to get your very own screen saver up and, er, saving.

Here's What We're Gonna Do

Let's start by taking a look at the process for creating a screen saver in OS X. Here are the broad steps:

  • Create a new screen saver project in Xcode.
  • Edit our .h file.
  • Override methods and write other code in our .m file.
  • Build the project to create a .saver package.
  • Install the .saver package by putting it into the Library/Screen Savers/ folder.
  • Open System Preferences and see a preview of our screen saver.
  • Enjoy the savings!

We'll go through each of these steps in greater depth now.

Little Help

The basic magic that makes screen savers so easy is the Screen Saver framework in Cocoa. This framework defines the ScreenSaverView class, which is a subclass of NSView. By creating your own subclass of ScreenSaverView and adding some code, you define your screen saver. The Screen Saver framework also defines the class ScreenSaverDefaults, which you can use for handling preferences for your saver. Along with these classes, the framework provides some handy utility functions you can use in your code.

We'll go over some of the most interesting methods and functions in the ScreenSaverView class. You will rarely call methods defined by ScreenSaverView - most of the work is creating your own subclass and override some methods.

initWithFrame:isPreview:

- (id)initWithFrame:(NSRect)frame isPreview:(BOOL)isPreview

You override initWithFrame in your ScreenSaverView subclass. The system calls initWithFrame when the screen saver is about take over the screen or is selected in System Preferences. The frame parameter is the frame rectangle for the view. The isPreview parameter tells whether the screen saver is actually being invoked or is merely being asked to preview itself in System Preferences (as shown in Figure 1).


Figure 1. You can preview the screen saver in a little box in System Preferences. In your code, you can tell whether the screen saver is drawing full-screen or in the preview box.

startAnimation

- (void) startAnimation

The system calls startAnimation right before the screen saver is about to start drawing. You should override startAnimation to set up your screen saver's initial state, such as setting line widths or loading images. You should call the inherited implementation, or bad things might happen, such as incorrect drawing, or all water on earth instantaneously evaporating.

animateOneFrame

- (void) animateOneFrame

This is where your screen saver gets to show off its amazing graphical skills. Mac OS X asks your screen saver to do its drawing by calling animateOneFrame repeatedly. You can actually do your drawing in animateOneFrame or in drawRect, or even a little in both places. If you make any changes here that require further redrawing, your implementation should call setNeedsDisplay:YES, which will cause drawRect to be called.

drawRect

- (void) drawRect:(NSRect)rect 

Override drawRect to draw the screen saver view. You can do your drawing in animateOneFrame, or you can do some or all of it here. rect is the rectangle you're drawing into, which is handy to have when you want to erase the view and start drawing afresh.

stopAnimation

- (void) stopAnimation 

When Mac OS X wants your screen saver to stop doing its thing, it calls stopAnimation. You can override stopAnimation to release resources or do any other cleanup you want before your screen saver goes away.

Saving Time

Now that you're familiar with the cast of characters in ScreenSaverView, let's go ahead and code up our screen saver. To start, we'll open Xcode and create a new project of type Screen Saver (see Figure 2).


Figure 2. Creating a new Screen Saver project gets you started with the Screen Saver framework, including your own subclass of ScreenSaverView.

This proves that Xcode already knows about the screen saver framework, which saves us plenty of work. Our new project already contains a subclass of ScreenSaverView, and we already have the usual .h and .m files. We'll edit the .h file that Xcode gives us until it looks like this:

#import <ScreenSaver/ScreenSaver.h>


@interface SaveyerView : ScreenSaverView 
{
   NSBezierPath *path;
}


@end

The header file is pretty darn basic. All we do here is create a subclass of ScreenSaverView and add an NSBezierPath object to keep track of what we're drawing.

Now let's get into the implementation files and see what we can find. When we told Xcode to create a new ScreenSaver project, it start us off with some code, including the implementation for initWithFrame:isPreview:, the designated initializer. In this case, we're able to use the supplied code for initWithFrame without any changes:

- (id)initWithFrame:(NSRect)frame isPreview:(BOOL)isPreview
{
    self = [super initWithFrame:frame isPreview:isPreview];
    if (self) {
        [self setAnimationTimeInterval:1/30.0];
            // Draw 30 frames per second
    }
    return self;

The code here starts by calling the inherited implementation. After that, we use setAnimationTimeInterval to tell Mac OS X that we want our screen saver to draw 30 frames per second. As I mentioned, this is the default code that Xcode writes for this method. You can modify it if you want to perform some other task when the screen saver starts up. For example, if your screen saver has user-settable options, you can handle them here.

Next, we'll take a look at our startAnimation method, which the system calls right before asking our screen saver to start drawing. Our implementation of startAnimation begins by calling the inherited implementation. Then, we create our Bezier path and choose a nifty line join style:

- (void)startAnimation
{
   NSPoint x;

   [super startAnimation];
	
   path = [[NSBezierPath alloc] init];
      // We'll use a Bezier path for drawing

   [path setLineJoinStyle: NSRoundLineJoinStyle];	
      // Just for fun, connect the lines with
      // a round joint

When the system asks our screen saver to get ready to draw, we can call the view's isPreview method to see if we're being asked to draw on the full screen or in the little preview box in System Preferences (as shown back in Figure 1).

We can use the result of isPreview to make decisions about just what to draw. In our screen saver, we'll make the lines skinny for the preview, and fatter for the real, full-screen version:

   if ([self isPreview])
      // When drawing a preview, make the lines
      // much thinner than when saving screens.
   {
      [path setLineWidth: 0.0];
      // This is the thinnest possible line width
   }
   else
   {
      [path setLineWidth: 10.18];
      // This line width was chosen at random.
      // OK, actually, it's my son's birthdate.
   }

Our last task here is to get the Bezier path started. We'll do that by picking a random starting point and moving the path there:

   x = SSRandomPointForSizeWithinRect 
         (NSMakeSize (0,0), [self bounds]);
      // Call utility function to get a random point

   [path moveToPoint:x];
      // Start the path at the random point
}

We get a random point by calling SSRandomPointForSizeWithinRect, a handy function provided by the screen saver framework for just this purpose. Hooray for handy functions! Then, we simply move the path pen to that random point to start it out.

Everything that starts must end, and the next method we define is stopAnimation, which is called when the system doesn't need the screen saver to draw any more. Here's our implementation of stopAnimation:

- (void)stopAnimation
{
   [super stopAnimation];
	
   [path release];
         // Release the path

   path = nil;
         // Tell our screen saver view that there's no path
}

The standard stopAnimation provided by Xcode simply calls the inherited implementation. In our version, we keep that super call, and add code to release the Bezier path object and set the path instance variable to nil.

Every time the system wants our screen saver to draw another piece, it calls our animateOneFrame method. Let's take a look at that. First, we'll call that convenient SSRandomPointForSizeWithinRect utility function to get another random point:

- (void)animateOneFrame
{
    NSPoint x;
	
   x = SSRandomPointForSizeWithinRect 
         (NSMakeSize (0,0), [self bounds]);
            // Get a random point to extend the Bezier path

We want our screen saver to draw a bunch of lines on the screen, and every so often, we want it to erase the lines and start over. Let's say we want 50 lines at a time, in honor of our 50 states. If we haven't reached 50 yet, we add the new random point to the path:

if ([path elementCount] < 50)
      // Draw 50 lines before erasing
      {
         [path lineToPoint: x];
            // If we don't have 50 yet, add the 
            // new point to the line
      }

Once we have 50 points in the path, we want to reset the path by callously discarding all points and then start building it up again:

      else
      {
         [path removeAllPoints];
         [path moveToPoint:x];
            // If we do have 50, clean out the path
            // and get ready to start over
      }

We finish by telling the system that we've messed with the path and it needs to be redrawn by calling the screen saver view's drawRect method. Alternatively, we could do the actual drawing right here in animateOneFrame:

   [self setNeedsDisplay:YES];
      // Tell the system that something has changed
      // and drawRect should be called
}

The actual drawing happens in drawRect, which we'll look at NeXT. We start by calling the inherited drawRect, which by default erases the background to black.

- (void)drawRect:(NSRect)rect
{
   NSColor *color;

   [super drawRect:rect];

We then choose a pretty color, and call set to make sure that the drawing happens in that color. Then we call stroke on the Bezier path object to actually draw the thing:

   color = [NSColor colorWithCalibratedRed:(0.0) 
                  green:(1.0) blue:(1.0) alpha:(1.0)];

   [color set];
      // Set the color to teal. Go Sharks!
	
   [path stroke];
      // Draw the Bezier path 
}

The last method we implement is our version of dealloc. The view's Bezier path is the only allocated object we have to worry about, so our method looks like this:

- (void) dealloc
{
   [path release];
      // Release the Bezier path

   [super dealloc];
}

Put Me In, Coach

When we have all the source code done, we build our project. If everything builds OK, a file with the suffix .saver ends up in the project's build folder. To install the screen saver, start by quitting System Preferences if it's running. Then move or copy the .saver file into the /Library/Screen Savers directory. You can put it in ~/Library/Screen Savers if you want to keep it all to yourself and prevent other users from seeing it.

Once our screen saver is in the folder, you can start System Preferences, click Desktop & Screen Saver, click the Screen Saver tab, and select our screen saver in the list. You should see the skinny lines in the preview mode. Then click Test, and observe the big teal lines with their round elbows. There you go! You can get this month's code at http://www.papercar.com/mt/Jun04.zip

If you're interested in making your own screen savers, there are lots of directions you can go from here. Add user-settable options by overriding the hasConfigureSheet and configureSheet methods. Use random colors. Do some much fancier drawing in your animateOneFrame method - for example, draw shapes, use curveToPoint instead of lineToPoint, or load images from disk. Whatever you do, have fun, and remember: the screen you save may be your own.


Scott Knaster writes books, including the recently published Mac Toys and the brand-new Hacking iPod and iTunes, both from Wiley Publishing. Scott can't read and listen to vocal music at the same time. Scott writes these little bios in the third person. Write to Scott at scottk@mactech.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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.