About View

View Geometry

Frame & Bounds

Graphically, a view can be regarded as a framed canvas. The frame locates the view in its superview, defines its size, and clips drawing to its edges, while the canvas hosts the actual drawing. The frame can be moved, resized, and rotated in the superview and the view's content moves with it. Similarly, the canvas can be shifted, stretched, and rotated, and the view contents move within the frame.

A view tracks its size and location using two rectangles: a frame rectangle and a bounds rectangle. The frame rectangle defines the view's location and size in the superview using the superview’s coordinate system. The bounds rectangle defines the interior coordinate system that is used when drawing the contents of the view, including the origin and scaling.

frame用于在其父view中使用父view的坐标系统中定义view的location 和 size。 Bounds定义一个内部的坐标系统,当绘制view的内容时,就要用这个坐标系统,也包括起点和缩放。

If the size of the bounds rectangle differs from the frame rectangle, the content is stretched or compressed so that all the contents within the bounds are displayed in the view.

Transforming the Coordinate System

By default, a view's coordinate system is based at (0.0, 0.0) in the lower-left corner of its bounds rectangle, its unit square (the size of a 1.0 by 1.0 rectangle) is the same size as those of its superview, and its axes are parallel to that of its frame rectangle. The coordinate system of a view can be changed in four distinct ways: It can be translated, scaled, flipped, or rotated.

To translate or scale the coordinate system, you alter the view's bounds rectangle. Changing the bounds rectangle sets up the basic coordinate system with which all drawing performed by the view begins. Concrete subclasses of NSView typically alter the bounds rectangle immediately as needed in their initWithFrame: methods or upon loading a nib file that contains the view.

The method for changing the bounds rectangle is setBounds:, which both positions and scales the canvas. The origin of the rectangle provided to setBounds: becomes the lower-left corner of the bounds rectangle, and the size of the rectangle is made to fit in the frame rectangle, effectively scaling the view's drawn image.

当改变了坐标系统后,需要调用setNeedsDisplay,将view设置为需要重新绘制,或者调用display立刻重新绘制view。

NSView objects marked as needing display are automatically redisplayed on each pass through the application’s event loop. (View objects that need to redisplay before the event loop comes around can of course immediately be sent the appropriate display... method.)

参考文档:

1. https://developer.apple.com/library/mac/documentation/cocoa/conceptual/CocoaViewsGuide/Coordinates/Coordinates.html#//apple_ref/doc/uid/TP40002978-CH10-SW1

2. https://developer.apple.com/library/mac/documentation/cocoa/Conceptual/CocoaDrawingGuide/Transforms/Transforms.html#//apple_ref/doc/uid/TP40003290-CH204

原文地址:https://www.cnblogs.com/whyandinside/p/3429250.html