Coordinate system

A coordinate system is a two-dimensional space in which you position, size, transform, and draw your application’s visible objects, and in which you locate user events. Applications in iOS and OS X rely on a coordinate system that locates points using horizontal and vertical axes (that is, an x-axis and a y-axis) that intersect at a common origin point (0.0, 0.0). From the origin, positive values increase in one direction along either axis; negative values increase in the opposite directions. You express a point in this coordinate space as a pair of floating-point numbers in user-space units, which are unpinned to any units in device space such as pixels. Drawing almost always occurs in the sector of a coordinate space where both x-axis and y-axis values are positive.

Art/window_coordinate.jpg

Coordinate Systems Can Have Different Drawing Orientations

The default coordinate system for views in iOS and OS X differ in the orientation of the vertical axis:

  • OS X. The default coordinate system has its origin at the lower left of the drawing area; positive values extend up and to the right from it. You can programmatically “flip” a view’s coordinate system in OS X.

  • iOS. The default coordinate system has its origin at the upper left of the drawing area, and positive values extend down and to the right from it. You cannot change the default orientation of a view’s coordinate system in iOS—that is, you cannot “flip” it.

Art/flipped_coordinates.jpg

Windows and Views Have Their Own Coordinate Systems

An application has multiple coordinate systems in play at any time. A window is positioned and sized in screen coordinates, which are defined by the coordinate system for the display. The window itself represents the base coordinate system for all drawing and event handling performed by its views. Each view in the window maintains its own local coordinate system for drawing itself; this coordinate system is defined by a view’s bounds property. A view’s frame property expresses its location and size in the coordinate system of its superview; that same view, in turn, provides the base coordinate system for positioning and sizing its subviews.

Both the AppKit and UIKit frameworks provide methods for converting points and rectangles between the coordinate systems of a view and another view, a view and its window, and (on OS X) the screen and the window. An application locates mouse, tablet, gesture, and multi-touch events in the coordinate system of a window, but views can easily convert these to their local coordinate systems.

You can also map points from one coordinate space to another using a two-dimensional mathematical array known as a transform. Using transforms, you can easily scale, rotate, and translate content in two-dimensional space.