Chapter 15. Drawing in a Rectangle: More Fun with Cocoa Views

In the previous chapter, we saw how to draw in an NSView using Quartz drawing commands. The purpose of this chapter is to learn more about NSView’s drawRect: method and Cocoa views in general. Recall that to us a view is any object that is a member of the NSView class or any of its subclasses (just as a responder is any object that is a member of the NSResponder class or any of its subclasses).

The Advantages of NSView’s drawRect: Method

As we saw in Chapter 14, the main advantage of the drawRect: method is that it localizes all of the drawing commands necessary to draw your NSView in a single method. In practice, this allows you to separate the code in your application that controls layout from the code that controls drawing. This leads to an application that is cleaner, easier to maintain, and, in many cases, more efficient.

The drawRect: method can be invoked under a variety of circumstances:

  • The NSView draws “itself” the first time that it is displayed in its window.

  • If the NSView’s window is not buffered, the NSView redraws itself every time the window is exposed.

  • If the NSView is displayed in an NSScrollView, it redraws part of itself whenever the user makes a new part of it visible by dragging the scrollbar.

  • If the user wants to print the NSView, the NSView’s drawRect: method is invoked to perform the appropriate Quartz calls for the given device.

  • If the user wants to save the contents of the NSView as a PDF file, the NSView can generate the PDF file too.

Putting the drawing of an NSView in drawRect: makes redisplay happen in the most efficient manner possible and lets your view print and create PDF files without requiring any additional code.

NSView’s drawRect: method is designed to be overridden by the programmer. The drawRect: method in NSView itself does nothing; when you subclass the NSView class, you must override the do-nothing drawRect: method to handle the drawing for your custom NSView.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.239.182