CAMediaTiming

The CAMediaTiming protocol is implemented by CALayer and CAAnimation. It models hierarchical timing systems, where each object describes the mapping from its parent object’s time value to local time.

Absolute time is defined as Mach time converted to seconds. To facilitate querying the current absolute time, the CACurrentMediaTime function is provided.

The transition from parent time to local time is divided into two phases:

  1. Convert to Active Local Time. This includes the point in time the object appears in the parent timeline and how fast it plays relative to the parent.
  2. Switch from active time to Basic Local Time. The timing model allows an object to repeat its base duration multiple times, optionally playing before repeating.
@protocol CAMediaTiming
...
@end
Copy the code

CACurrentMediaTime

Returns the current absolute time in seconds.

CFTimeInterval CACurrentMediaTime(void);
Copy the code

Return Value: CFTimeInterval obtained by calling mach_absolute_time() and converting the result to seconds.

Animation Start Time

beginTime

Specifies the start time of the receiver relative to its parent, if applicable. Default is 0.

/* The begin time of the object, in relation to its parent object, if applicable. Defaults to 0. */
@property CFTimeInterval beginTime;
Copy the code

The start time of the object (relative to its parent), if applicable. Default is 0.

timeOffset

Specifies an additional time offset in the local time of the activity, preset to 0.

/* Additional offset in active local time. * i.e. to convert from parent time tp to active local time t: t = (tp - begin) * speed + offset. * One use of this is to "pause" a layer by setting 'speed' to zero and 'offset' to a suitable value. * Defaults to 0. */
@property CFTimeInterval timeOffset;
Copy the code

The offset increased by the local time of the activity. For example; Local time from parent tp to active t: t = (tP-begin) * speed + offset. One use is to pause (“pause”) the layer by setting speed to zero and offset to an appropriate value. Default is 0.

Repeating Animations

repeatCount

Determines how many times the animation will be repeated.

/* The repeat count of the object. May be fractional. Defaults to 0. */
@property float repeatCount;
Copy the code

It could be a fraction (type float). If repeatCount is 0, it is ignored. The default value is 0. If both repeatDuration and repeatCount are specified, the behavior is undefined.

repeatDuration

Determines how many seconds the animation will repeat. (The duration of the object’s repetition. Default is 0.

/* The repeat duration of the object. Defaults to 0. */
@property CFTimeInterval repeatDuration;
Copy the code

The default value is 0. If repeatDuration is 0, it is ignored. If both repeatDuration and repeatCount are specified, the behavior is indeterminate.

Duration and Speed

duration

Specifies the base duration of the animation in seconds. Default is 0.

/* The basic duration of the object. Defaults to 0. */
@property CFTimeInterval duration;
Copy the code

The base duration of the object. Default is 0.

speed

Specifies how the time is mapped from the parent time space to the time space of the receiver.

/* The rate of the layer. Used to scale parent time to local time, * e.g. if rate is 2, local time progresses twice as fast as parent time. * Defaults to 1. */
@property float speed;
Copy the code

For example, if speed is 2.0, the progress of local time is twice that of parent time. The default is 1.0.

Rate of layer. Used to scale the parent time to local time, for example if the ratio is 2, the progress of local time is twice that of the parent time.

Playback Modes

autoreverses

Determines whether the receiver plays backwards when it is done.

/* When true, the object plays backwards after playing forwards. Defaults to NO. */
@property BOOL autoreverses;
Copy the code

If true, the object is played forward and backwards. The default value is NO.

fillMode

Determines whether the presentation of the receiver is frozen or deleted after the expiration of its validity period. The possible values are specified in Fill Modes. The default is kCAFillModeRemoved.

/* Defines how the timed object behaves outside its active duration. * Local time may be clamped to either end of the active duration, * or the element may be removed from the presentation. * The legal values are 'backwards', 'forwards', 'both' and 'removed'. * Defaults to 'removed'. */
@property(copy) CAMediaTimingFillMode fillMode;
Copy the code

Defines the behavior of a Timed Object outside of its activity duration. The local time can be fixed at either end of the activity duration, or the element can be removed from the presentation. Legal values are forwards, forwards, both, and removed. The default is Removed.

Fill Modes

These constants determine the behavior of the timed object after its activity duration is completed. They are used with the fillMode attribute.

typedef NSString * CAMediaTimingFillMode NS_TYPED_ENUM;
/* `fillMode' options. */

CA_EXTERN CAMediaTimingFillMode const kCAFillModeForwards   API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
CA_EXTERN CAMediaTimingFillMode const kCAFillModeBackwards  API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
CA_EXTERN CAMediaTimingFillMode const kCAFillModeBoth       API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
CA_EXTERN CAMediaTimingFillMode const kCAFillModeRemoved    API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
Copy the code
  • Kcafillmodeforward: After animation is completed, the Receiver is still visible in its final state.
  • kCAFillModeBackwards: The receiver clamps values before zero to zero when the animation is completed.
  • KCAFillModeBoth: Receiver fixes values at both ends of the object’s space and time.
  • KCAFillModeRemoved: Receiver will be removed from presentation after animation is complete.

CAAction

Interface that allows an object to respond to actions triggered by a CALayer change. (Protocol with only one proxy method, which the CAAnimation class follows)

When queried using an Action identifier (key path, external action name, or predefined action identifier), CALayer returns the corresponding action object (which must implement the CAAction protocol), And sent to its runActionForKey: object: the arguments: the message.

Responding to an action

– runActionForKey:object:arguments:

Call to trigger the action specified by the identifier.

Key: indicates the identifier of the action. An identifier can be a key or key path relative to an object, any external action, or one of the action identifiers defined in a CALayer. AnObject: the CALayer on which the action occurs. Dict: a dictionary containing the parameters associated with this event. It could be nil.

/** Action (event handler) protocol. **/

@protocol CAAction

- (void)runActionForKey:(NSString *)event object:(id)anObject arguments:(nullable NSDictionary *)dict;

@end

/** NSNull protocol conformance. **/

@interface NSNull (CAActionAdditions) <CAAction>

@end
Copy the code

/* Called to trigger the event named ‘path’ on the receiver.

* Call to trigger an event named ‘event’ on the receiver.

  • The object (e.g. the layer) on which the event happened is ‘anObject’.
  • The object on which the event occurs (for example, CALayer) is ‘anObject’.
  • The arguments dictionary may be nil, if non-nil it carries parameters associated with the event.
  • The parameter dictionary may be nil, or if it is not nil, it carries the parameters associated with the event.

* /

CALayerDelegate

CALayer’s delegate object needs to follow this protocol to respond to Events associated with CALayer.

@protocol CALayerDelegate <NSObject>
@optional // The CALayerDelegate protocol methods are optional. @endCopy the code

You can implement methods of this protocol to provide CALayer content, handle sublayers layout, and provide custom animation actions to perform. The object that implements this protocol must be assigned to the Delegate property of the CALyer object.

In iOS, the layer delegate of a View is the View itself by default. The following example code is printed:

NSLog(@"😻😻 view itself: %@", self.view);
NSLog(@"😻😻 View's layer delegate: %@", self.view.layer.delegate);
// Console print:😻😻 view itself: <UIView:0x7fcdf090b170; frame = (0 0; 390 844); autoresize = W+H; layer = <CALayer: 0x6000038df680>> 😻😻 Layer delegate of view: <UIView:0x7fcdf090b170; frame = (0 0; 390 844); autoresize = W+H; layer = <CALayer: 0x6000038df680>>
Copy the code

Providing the Layer’s Content

– displayLayer:

Tell the delegate to perform the display.

- (void)displayLayer:(CALayer *)layer;
Copy the code

Layer: CALayer whose content needs to be updated.

– displayLayer: The delegate method is called when a CALayer is marked to reload its contents, usually started by the setNeedsDisplay method (flag). A typical update technique is to set the contents property of a CALayer.

If this delegate method is implemented, it is called by the default implementation of the -display method, in which case it should implement the entire display process (usually by setting the contents property).

– drawLayer:inContext:

Tell the delegate to use CALayer’s CGContextRef for the display.

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx;
Copy the code

Layer: The CALayer whose content needs to be drawn. CTX: Graphic context for drawing. The graphics context contains the appropriate scale factor to draw to the target screen.

The drawLayer:inContext: delegate method is called when a CALayer is marked to reload its contents, usually using the setNeedsDisplay method flag. If the delegate implements the displayLayer: method, it is not called. Vectors can be drawn using context, such as curves and lines, or images can be drawn using the Draw (_:in:byTiling:) method.

Important: If the delegate implements the displayLayer: method, this method will not be called.

If this delegate method is implemented, it is called by the default implementation of the -drawinContext: method.

– layerWillDraw:

Notification delegate is about to draw.

- (void)layerWillDraw:(CALayer *)layer API_AVAILABLE(macos(10.12), ios(10.0), watchos(3.0), tvos(10.0));
Copy the code

Layer: the CALayer whose content will be drawn.

Call the layerWillDraw: method before drawLayer:inContext:. You can use this method to configure any CALayer state that affects contents, such as contentsFormat and Opaque, before drawLayer:inContext:.

Important: If the delegate implements the displayLayer: method, this method will not be called.

If implemented, this delegate method is called by the default implementation of the -display method. Allows delegates to configure any CALayer state that affects contents, such as contentsFormat and Opaque, before -drawLayer :InContext:. If the delegate implements -displayLayer, this method is not called.

Laying Out Sublayers

– layoutSublayersOfLayer:

Tell the delegate that CALayer’s bounds have changed.

- (void)layoutSublayersOfLayer:(CALayer *)layer;
Copy the code

Layer: CALayer that needs to lay out its sublayers.

LayoutSublayersOfLayer: the method is called when a CALayer’s bounds changes, for example by changing the size of its frame. This approach can be implemented if you need precise control over the layout of CALayer’s Sublayers.

Called by the default -LayoutSublayers implementation before checking the Layout Manager. Note that the layout manager is ignored if the delegate method (-layoutsublayersoflayer 🙂 is called.

Providing a Layer’s Actions

– actionForLayer:forKey:

Returns the default action for the actionForKey: method.

- (nullable id<CAAction>)actionForLayer:(CALayer *)layer forKey:(NSString *)event;
Copy the code

Layer: CALayer as action target. Event: Identifier of the action.

Return Value: Object that implements the CAAction protocol, nil if the delegate does not specify behavior for the specified event.

The delegate of the CALayer that implements this method returns the action for the specified key and stops any further searches (that is, does not return the action or + defaultActionForKey for the same key in CALayer’s Actions dictionary: Specified action).

If this delegate method is implemented, it is called by the default implementation of the -actionForKey: method. The object implementing the CAAction protocol should be returned. If the delegate does not specify the behavior of the current event, it may return nil. Returning an empty object (that is, [NSNull null]) explicitly forces no further search. (that is, + defaultActionForKey: the method will not be called.)

CAMediaTiming, CAAction, CALayerDelegate summary

Here read CAMediaTiming, CAAction, CALayerDelegate three protocol. CAAnimation follows the CAMediaTiming and CAAction protocols, CALayer follows the CAMediaTiming protocol, and CALayerDelegate is the protocol that CALayer’s delegate follows.

  • CAMediaTiming protocol control animation start time (beginTime, timeOffset property), set the number of repeated animation or repeatCount, repeatDuration Property), sets the animation’s duration and speed (the duration, speed properties), the animation’s playback mode (whether autoreverses will be played after the animation ends, or fillMode forward, backward, both ends, or remove after the animation ends).
  • The CAAction protocol is only followed by the CAAnimation class, with only one delegate method- runActionForKey:object:arguments:Used in response to triggering an Action when a CALayer changes. (Executes a CAAnimation object added to CALayer)
  • The CALayerDelegate protocol is a protocol that the delegate provided to a CALayer must obey. It implements three functions: providing the content of a CALayer and laying out the CALayer sublayers (- layoutSublayersOfLayer:), provide layer operations (- actionForLayer:forKey:). But all of its protocol methods are optional by default (@optional). Among them- displayLayer:- drawLayer:inContext:Two different ways to deliver content to CALayer, but- displayLayer:Execution level higher than- drawLayer:inContext:When CALayer’s delegate is implemented- displayLayer:Method is not called again- drawLayer:inContext:Methods.- displayLayer:Delegate methods usually call it at CALayersetNeedsDisplayThe method is called when CALayer needs to reload its contents, and CALayer’s- displayThe default implementation of the method calls- displayLayer:Delegate method. Similarly, when- displayLayer:When the delegate method is not implemented,- drawLayer:inContext:Delegate methods usually call it at CALayersetNeedsDisplayThe method is called when CALayer needs to reload its contents, unlike CALayer’s- drawInContext:The default implementation of the method calls- drawLayer:inContext:Delegate method. while- layerWillDraw:The client rule is in- drawLayer:inContext:Call before. You can use this method in- drawLayer:inContext:The previous configuration affects any CALayer state of contents, such as contentsFormat and Opaque.

So let’s take a closer look at CALayer’s documentation.

CALayer

Objects that manage image-based content and allow you to animate that content. (Inherits from NSObject and follows the CAMediaTiming protocol)

API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0))
@interface CALayer : NSObject <NSSecureCoding, CAMediaTiming>
{
@private
  struct _CALayerIvars {
    int32_t refcount;
    uint32_t magic;
    void *layer;
#ifTARGET_OS_MAC && ! TARGET_RT_64_BIT
    void * _Nonnull unused1[8];
#endif
  } _attr;
}
Copy the code

Overview:

Layers are typically used to provide a backing store for the View, but can also be used to display content without the view. The main job of layer is to manage the visual content that you provide, but layer itself also has visual attributes that can be set, Examples include background color, border, and shadow. In addition to managing visual content, Layer maintains information about the geometry of its content (such as its position, size, and transform), which is used to display the content on the screen. Modifying the properties of a layer is a way to start an animation on the content or geometry of the layer. The Layer object encapsulates the duration and pace of the layer and its animation through the CAMediaTiming protocol, which defines the timing information of the layer.

If the Layer object is created by the View, the view will normally automatically specify itself as a Layer delegate, and this relationship should not be changed. For the layers you created yourself, you can assign a Delegate object to it and use that object to dynamically supply the contents of the Layer and perform other tasks. Layer may also have layoutManager objects (assigned to the layoutManager property) to manage the layout of sublayers (sublayers) separately.

Creating a Layer

+ layer

Create and return an instance of the Layer object.

+ (instancetype)layer;
Copy the code

Return Value: initializes the Layer object; If initialization fails, nil is returned.

If you are a subclass of CALayer, you can override this method and use this function to provide instances of specific subclasses.

– init

Returns an initialized CALayer object.

- (instancetype)init;
Copy the code

This is the designated initializer for the Layer object that is not in the Presentation Layer.

– initWithLayer:

Overrides to copy or initialize custom fields at the specified layer.

Core Animation uses this initializer to create a shadow copy of layers, for example as Presentation Layers. Subclasses can override this method to copy the instance variable into the Presentation Layer (subclasses should then call the superclass). Calling this method in any other case will result in undefined behavior.

- (instancetype)initWithLayer:(id)layer;
Copy the code

Layer: Layer from which custom fields should be copied.

Return Value: Layer instance of any custom instance variable copied from layer.

This initializer is used to create a shadow copy of layer, for example, for the presentationLayer method. Using this method in any other situation will result in uncertain behavior. For example, do not use this method to initialize a new layer with the contents of an existing layer.

If you want to implement a custom Layer subclass, you can override this method and use it to copy the value of the instance variable into a new object. A subclass should always call a superclass implementation.

This method is the designated initializer for each layer object in the Presentation Layer.

Accessing Related Layer Objects

– presentationLayer

Returns a copy of the Presentation Layer object that represents the state of the layer currently displayed on the screen.

- (nullable instancetype)presentationLayer;
Copy the code

Return Value: a copy of the current Presentation Layer object.

The Layer object returned by this method provides an approximation of the layer currently displayed on the screen. During animation, you can retrieve this object and use it to get the current values of those animations.

The sublayers, mask, and superlayer attributes of the return layer return the corresponding objects from the Presentation tree (not the model tree). This pattern also applies to any read-only Layer method. For example, return the hitTest: method of the object to query the Layer object in the Presentation Tree.

Returns a copy of the CALayer containing all the properties that were the same as when the current transaction began, with all the active animations applied. This is very close to the version of CALayer currently displayed. If the CALayer has not been committed, nil is returned. Trying to modify the returned CALayer object in any way will have an indeterminate effect. (The returned CALayer object should only be used to read its current various properties.) The sublayers, mask, and Superlayer properties of the returned CALayer object return the Presentation versions of those properties. This will execute the read-only CALayer method. For example, calling -hitTest on the CALayer object returned by -PresentationLayer will query the Presentation values of the Layer Tree.

– modelLayer

Returns the Model Layer object associated with the Receiver, if any.

- (instancetype)modelLayer;
Copy the code

Return Value: represents a CALayer instance of the underlying Model layer.

Calling this method on a CALayer in the Presentation Tree returns the corresponding CALayer object in the Model Tree. This method returns a value only if a transaction involving a change in the presentation layer is in progress. If there are no ongoing transactions, the result of calling this method is indeterminate.

When the result of the -PresentationLayer method is up-scaled, the base layer with the current model value is returned. Returns the receiver when the non-presentation layer is up-regulated. The result of calling this method after the transaction that generated the presentation layer is uncertain.

The “presentation tree” and “model tree” involved in the -PresentationLayer and -Modellayer functions above are explained in detail later in the Core Animation documentation.

(Accessing the Delegate of CALayer)

delegate

CALayer’s delegate object. (Delegate is the weak property of the CALayerDelegate protocol.)

@property(nullable, weak) id <CALayerDelegate> delegate;
Copy the code

You can use delegate objects to provide layer content, handle the layout of any sublayers, and provide custom actions in response to layer-related changes. The object you assign to this property should implement one or more methods of the CALayerDelegate informal protocol. For more information about the protocol, see CALayerDelegate Protocol analysis above.

In iOS, if a layer is associated with a UIView object, this property must be set to the UIView that owns that CALayer. (In iOS UIView defaults to being the delegate object for its layer property, but defaults to nil for self-created CALayer objects)

Providing the Layer’s Content

contents

An object that provides CALayer content. Animatable. (strong modifies an attribute of type ID)

@property(nullable, strong) id contents;
Copy the code

The default value for this property is nil.

If you use CALayer to display static images, you can set this property to CGImageRef, which contains the image to display. (On macOS 10.6 and later, you can also set this property to an NSImage object.) Assigning a value to this property causes CALayer to use your image instead of creating a separate backing store.

If the layer object is bound to a UIView object, avoid setting the content of this property directly. The interaction between the view and the layer usually causes the view to replace the contents of this property during subsequent updates.

contentsRect

A rectangle in unit coordinate space that defines the part of the CALayer content that should be used. Animatable.

@property CGRect contentsRect;
Copy the code

The default is a unit rectangle (0.0, 0.0, 1.0, 1.0).

If pixels outside the unit rectangle are requested, the edge pixels of the content image are expanded outward.

If an empty rectangle is provided, the result is indeterminate.

Rectangles in normalized image coordinates define the subrectangles that will be drawn to the contents property in the layer. If pixels outside the unit rectangle are requested, the edge pixels of the content image are expanded outward. If an empty rectangle is provided, the result is indeterminate. Default is a unit rectangle [0, 0, 1, 1]. Animatable.

contentsCenter

Used to define how to scale a layer’s content when resizing it. Animatable.

@property CGRect contentsCenter;
Copy the code

You can use this property to subdivide the layer content into a 3×3 grid. The value in this property specifies the position and size of the center rectangle in the grid. If the layer’s contentsGravity property is set to a resizing mode, resizing the layer will cause different scaling in each rectangle of the grid. The center rectangle is stretched in both dimensions, the upper and lower center rectangles are stretched horizontally only, the left and right center rectangles are stretched vertically only, and the quadrangle is not stretched at all. Therefore, you can use this technique to achieve a stretchable background or image using three or nine part images.

By default, the value in this property is set to unit rectangle (0.0,0.0) (1.0,1.0), which causes the entire image to scale in both dimensions. If the specified rectangle exceeds the unit rectangle, the result is undefined. The specified rectangle is applied only after the contentsRect property is applied to the image.

Note: If the width or height of the rectangle in this property is small or 0, the value is implicitly changed to the width or height of a single source pixel centered at the specified location.

The rectangle in the normalized image coordinates defines the scale center portion of the contents image. When an image is resized due to its contentsGravity property, the center portion implicitly defines a 3×3 grid that controls how the image is scaled to the size it was drawn. The center stretches in both directions. The top and bottom stretch only horizontally; The left and right parts are only vertically stretched; The four corners are not stretched at all. (This is commonly known as “9-slice scaling”.) The rectangle is interpreted after the effect of the contentsRect property is applied. The default is a unit rectangle [0, 0, 1, 1], which means the entire image will be scaled. As a special case, if the width or height is zero, it is implicitly adjusted to the width or height of a single source pixel centered at that location. If the rectangle extends outside the cell rectangle [0 0 1 1], the result is inconclusive. Animatable.

– display

Reload the contents of this layer.

- (void)display;
Copy the code

Do not call this method directly. CALayer calls this method to update the contents of CALayer when appropriate. If a CALayer has a delegate object, the method tries to call the delegate’s displayLayer: method, which the delegate can use to update the CALayer’s content. If the Delegate does not implement the displayLayer: method, this method will create the backing Store and call CALayer’s drawInContext: method to fill the backing store with content. The new backing Store will replace the previous content of this CALayer.

Subclasses can override this method and use it to set the contents property of CALayer directly. You can do this if your custom CALayer subclass treats layer updates differently.

Reload the contents of CALayer. Call the -drawinContext: method and update the contents property of CALayer. Usually, it is not called directly.

– drawInContext:

Draws the contents of a CALayer using the specified graphics context.

- (void)drawInContext:(CGContextRef)ctx;
Copy the code

CTX: The graphical context in which content is drawn. Context can be tailored to protect valid CALayer content. Hope to find to draw the actual area of the subclass can call CGContextGetClipBoundingBox.

The default implementation of this method does not itself do any drawing. If the CALayer’s delegate implements the -drawLayer :inContext: method, that method is called to actually draw.

Subclasses can override this method and use it to draw the contents of CALayer. When drawing, all coordinates should be specified at points in the logical coordinate space.

Called with the -display method when the contents property is updated. The default implementation does nothing. Context can be tailored to protect valid CALayer content. Hope to find to draw the actual area of the subclass can call CGContextGetClipBoundingBox ().

Modifying the Layer’s Appearance (Modifying the Appearance of a CALayer)

contentsGravity

A constant that specifies how CALayer’s contents jam or scaled within its bounds.

@property(copy) CALayerContentsGravity contentsGravity;
Copy the code

The possible Values for this property are listed in Contents Gravity Values.

The default value for this property is kCAGravityResize. (Resize content to fit the entire Bounds rectangle, which may be stretched out of shape)

Important: Contents Gravity constants The naming is based on the direction of the vertical axis. If the gravitational constant is used with vertical components (for example, kCAGravityTop), the contentsAreFlipped layer should also be examined. If this option is YES, kCAGravityTop aligns contents with the bottom of the CALayer, and kCAGravityBottom aligns contents with the top of the layer.

The default coordinate system for views in macOS and iOS differs in the direction of the vertical axis: in macOS, the origin of the default coordinate system is at the lower left corner of the drawing area and a positive value extends from the middle up, while in iOS, the origin of the default coordinate system is at the upper left corner of the drawing area and a positive value extends down from that coordinate system.

Figure 1 shows four examples that set different values for the layer’s contentsGravity property.

Figure 1 Different effects of setting a layer’s contents gravity

  1. Contents gravity is kCAGravityResize – the default
  2. Contents gravity is kCAGravityCenter
  3. Contents gravity is contentsAreFlipped ? kCAGravityTop : kCAGravityBottom
  4. Contents gravity is contentsAreFlipped ? kCAGravityBottomLeft : kCAGravityTopLeft

A string that defines how to map CALayer’s contents to its Bounds rectangle. Options are ‘Center’, ‘top’, ‘bottom’, ‘left’, ‘right’, ‘topLeft’, ‘topRight’, ‘bottomLeft’, ‘bottomRight’, ‘resize’, ‘resizeAspect’, ‘resizeAspectFill’. The default value is’ resize’. Note that ‘bottom’ always stands for minimum Y and ‘top’ always stands for maximum Y.

Contents Gravity Values

When the CALayer bounds are greater than the bounds of the content object, the content gravity constant specifies the position of the content object. They are used by the contentsGravity property.

CA_EXTERN CALayerContentsGravity const kCAGravityCenter API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
CA_EXTERN CALayerContentsGravity const kCAGravityTop API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
CA_EXTERN CALayerContentsGravity const kCAGravityBottom API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
CA_EXTERN CALayerContentsGravity const kCAGravityLeft API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
CA_EXTERN CALayerContentsGravity const kCAGravityRight API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
CA_EXTERN CALayerContentsGravity const kCAGravityTopLeft API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
CA_EXTERN CALayerContentsGravity const kCAGravityTopRight API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
CA_EXTERN CALayerContentsGravity const kCAGravityBottomLeft API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
CA_EXTERN CALayerContentsGravity const kCAGravityBottomRight API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
CA_EXTERN CALayerContentsGravity const kCAGravityResize API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
CA_EXTERN CALayerContentsGravity const kCAGravityResizeAspect API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
CA_EXTERN CALayerContentsGravity const kCAGravityResizeAspectFill API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
Copy the code
  • KCAGravityCenter: Content is centered horizontally and vertically in the Bounds rectangle.
  • KCAGravityTop: The content is horizontally centered on the top edge of the Bounds rectangle.
  • KCAGravityBottom: The content is horizontally centered on the bottom edge of the Bounds rectangle.
  • KCAGravityLeft: The content is centered vertically on the left edge of the Bounds rectangle.
  • KCAGravityRight: The content is centered vertically on the right edge of the Bounds rectangle.
  • KCAGravityTopLeft: The content is in the upper left corner of the Bounds rectangle.
  • KCAGravityTopRight: The content is in the upper right corner of the Bounds rectangle.
  • KCAGravityBottomLeft: The content is in the bottom left corner of the Bounds rectangle.
  • KCAGravityBottomRight: The content is in the bottom right corner of the Bounds rectangle.
  • KCAGravityResize: Resizes content to fit the entire Bounds rectangle. (May be stretched and deformed)
  • KCAGravityResizeAspect: Resizes the content to fit the Bounds rectangle, preserving the appearance of the content (preserving the width-to-height ratio). If the content does not completely fill the Bounds rectangle, the content will center on a partial axis.
  • KCAGravityResizeAspectFill: adjust the content to fill the bounds rectangle size, at the same time retain the appearance of content (retain wide high percentage). Content is centered on the axis it exceeds.

opacity

The opacity of receiver. Animatable.

@property float opacity;
Copy the code

The value of this property must be between 0.0 (transparent) and 1.0 (opaque). Values outside this range are restricted to either the minimum or maximum. The default value for this property is 1.0.

CALayer’s opacity, a value between 0 and 1. The default value is 1. Specifying values outside the range of [0,1] will produce indeterminate results. Animatable.

hidden

Indicates whether to hide the Boolean value of CALayer. Animatable.

@property(getter=isHidden) BOOL hidden;
Copy the code

The default value for this property is NO.

If true, this layer and its sublayers are not displayed. The default value is NO. Animatable.

masksToBounds

A Boolean value indicating whether to crop sublayers to the Bounds of the CALayer. Animatable.

@property BOOL masksToBounds;
Copy the code

When this property has a value of YES, Core Animation creates an implied clipping mask that matches CALayer’s bounds and includes any corner RADIUS effects. If you also specify a value for the mask property, multiply the two masks to get the final mask value.

The default value for this property is NO.

mask

Optional layer whose Alpha channel is used to mask CALaer content.

@property(nullable, strong) __kindof CALayer *mask;
Copy the code

The Alpha channel of a CALayer determines how much content and background can be displayed for that CALayer. Fully or partially opaque pixels allow the underlying content to be displayed, but fully transparent pixels block that content.

The default value for this property is nil. When configuring a mask, remember to set the size and position of the mask layer to ensure that it is properly aligned with the Mask’s CALayer.

The CALayer you assign to this property must not have a Superlayer. If so, the behavior is indeterminate.

A CALayer whose alpha channel acts as a mask to choose between a CALayer’s background and the result of synthesizing its content with its filtered background. Defaults to nil. The compositingFilter and backgroundFilters properties of the layer are ignored when used as a mask. When mask is set to New Layer, its superlayer must be nil, otherwise the behavior is indeterminate. Nested masks (a mask layer with its own mask) are not supported.

doubleSided

A Boolean value indicating whether a CALayer displays its contents when facing away from the viewer. Animatable.

@property(getter=isDoubleSided) BOOL doubleSided;
Copy the code

When this property has a value of NO, the layer hides its content when it faces away from the viewer. The default value for this property is YES.

cornerRadius

The radius to use when rounding CAlayer’s background. Animatable.

@property CGFloat cornerRadius;
Copy the code

Setting radius to greater than 0.0 allows CALayer to begin drawing rounded corners on its background. By default, corner Radius is not applied to images in the CALayer contents property; It only applies to CALayer background colors and borders. However, setting the masksToBounds attribute to YES will crop the content to rounded corners.

The default value for this property is 0.0.

maskedCorners

Defines which of the four corners receives a mask when the cornerRadius property is used. Default is all four corners.

@property CACornerMask maskedCorners API_AVAILABLE(macos(10.13), ios(11.0), watchos(4.0), tvos(11.0));
Copy the code

CACornerMask

Bit definition for the maskedCorners property.

typedef NS_OPTIONS (NSUInteger, CACornerMask)
{
  kCALayerMinXMinYCorner = 1U << 0,
  kCALayerMaxXMinYCorner = 1U << 1,
  kCALayerMinXMaxYCorner = 1U << 2,
  kCALayerMaxXMaxYCorner = 1U << 3};Copy the code

borderWidth

CALayer width of the border. Animatable.

@property CGFloat borderWidth;
Copy the code

When this value is greater than 0.0, CALayer will draw the border using the current borderColor value. The border is drawn from the receiver’s bounds based on the value specified in this property. It is composed on top of the receiver’s content and sublayers and contains the effect of the cornerRadius property.

The default value for this property is 0.0.

borderColor

CALayer border color. Animatable. (Type CGColorRef)

@property(nullable) CGColorRef borderColor;
Copy the code

The default value for this property is opaque black.

Retain the value of this property using Core Foundation retain/ Release semantics. This behavior occurs even though the property declaration appears to use the default assign semantics for object reservation.

backgroundColor

CALayer’s background color. Animatable.

@property(nullable) CGColorRef backgroundColor;
Copy the code

The default value for this property is nil.

Retain the value of this property using Core Foundation retain/ Release semantics. This behavior occurs even though the property declaration appears to use the default assign semantics for object reservation.

shadowOpacity

CALayer’s shadow opacity. Animatable.

@property float shadowOpacity;
Copy the code

The value in this property must be between 0.0 (transparent) and 1.0 (opaque). The default value for this property is 0.0.

The opacity of the shadow. The default value is 0. Specifying values outside the range [0,1] will give inconclusive results. Animatable.

shadowRadius

The blur radius, in points, used to render the CALayer shadow. Animatable.

@property CGFloat shadowRadius;
Copy the code

Specify radius The default value for this property is 3.0.

The blur radius used to create the shadow. The default value is 3.0. Animation can be set.

shadowOffset

The offset of the CALayer shadow, in points. Animatable.

@property CGSize shadowOffset;
Copy the code

The default value for this property is (0.0, -3.0).

shadowColor

CALayer shadow color. Animatable.

@property(nullable) CGColorRef shadowColor;
Copy the code

Retain the value of this property using Core Foundation retain/ Release semantics. This behavior occurs even though the property declaration appears to use the default assign semantics for object reservation.

Shadow color. The default is opaque black. Colors created from patterns are not currently supported. Animatable.

shadowPath

The shape of the CALayer shadow. Animatable.

@property(nullable) CGPathRef shadowPath;
Copy the code

The default value of this property is nil, which causes CALayer to use the standard Tandard shadow Shape. If you specify a value for this property, CALayer creates its shadow using the specified path instead of CALayer’s synthetic alpha channel. The path you provide defines the outline of the shadow. Use non-zero winding rules and fill with the current shadow color, opacity and blur radius.

Unlike most animatable properties, this property (like all CGPathRef animatable properties) does not support implicit animation. However, you can animate a path object using any concrete subclass of CAPropertyAnimation. Paths will interpolate as a linear mixture of “on-line” points; Off-line “points can be interpolated nonlinearly (to preserve continuity of curve derivatives). If two paths have different numbers of control points or segments, the result is undefined. If the path extends beyond the layer boundary, it will not be automatically clipped to the layer, only if the normal masking rules cause this to happen.

Specifying explicit paths can often improve rendering performance.

Retain the value of this property using Core Foundation retain/ Release semantics. This behavior occurs even though the property declaration appears to use the default assign semantics for object reservation.

When not null, this path defines the contour used to construct the layer’s shadow instead of using the layer’s composition Alpha channel. Render paths using non-zero winding rules. Explicitly specifying paths using this property can often improve rendering performance because the same path reference can be shared across multiple layers. After allocation, the path will be copied. Defaults to nil. Animatable.

Using Shadow Path for Special Effects

You can use the layer’s shadow paths to create special effects, such as emulating the shadows available in Pages.

Listing 1 shows the code needed to add the ellipse Shadow to the bottom of the layer to simulate the Pages Contact Shadow effect.

Listing 1 Creating a contact shadow path. Listing 1 Creating a contact shadow path

let layer = CALayer()
     
layer.frame = CGRect(x: 75, y: 75, width: 150, height: 150)
layer.backgroundColor = NSColor.darkGray.cgColor
layer.shadowColor = NSColor.gray.cgColor
layer.shadowRadius = 5
layer.shadowOpacity = 1
     
let contactShadowSize: CGFloat = 20
let shadowPath = CGPath(ellipseIn: CGRect(x: -contactShadowSize,
                                          y: -contactShadowSize * 0.5,
                                          width: layer.bounds.width + contactShadowSize * 2,
                                          height: contactShadowSize),
                        transform: nil)
     
layer.shadowPath = shadowPath
Copy the code

Figure 1 Layer with contact shadow effect

Listing 2 shows how to create a path to simulate the Pages Curved Shadow. The left, top, and right sides of the path are straight lines, while the bottom is a concave curve, as shown in Figure 2.

Figure 2 Shadow path for curved Shadow effect

Listing 2 Creating a curved shadow path

let layer = CALayer()
layer.frame = CGRect(x: 75, y: 75, width: 150, height: 150)
layer.backgroundColor = NSColor.darkGray.cgColor
     
layer.shadowColor = NSColor.black.cgColor
layer.shadowRadius = 5
layer.shadowOpacity = 1
     
let shadowHeight: CGFloat = 10
let shadowPath = CGMutablePath()
shadowPath.move(to: CGPoint(x: layer.shadowRadius,
                            y: -shadowHeight))
shadowPath.addLine(to: CGPoint(x: layer.shadowRadius,
                               y: shadowHeight))
shadowPath.addLine(to: CGPoint(x: layer.bounds.width - layer.shadowRadius,
                               y: shadowHeight))
shadowPath.addLine(to: CGPoint(x: layer.bounds.width - layer.shadowRadius,
                               y: -shadowHeight))
     
shadowPath.addQuadCurve(to: CGPoint(x: layer.shadowRadius,
                                    y: -shadowHeight),
                        control: CGPoint(x: layer.bounds.width / 2,
                                         y: shadowHeight))
     
layer.shadowPath = shadowPath
Copy the code

Figure 3 Layer with curved shadow effect

style

Optional NSDictionary, used to store property values not explicitly defined by CALayer

@property(nullable, copy) NSDictionary *style;
Copy the code

This NSDictionary can in turn have a style key that forms a hierarchy of default values. In hierarchical Style dictionaries, the shallowest value of the attribute is used. For example, style.somevalue takes precedence over style.style.somevalue.

If the Style Dictionary does not define a value for the attribute, CALayer’s + defaultValueForKey: method is called. The default value for this property is nil.

The following keywords do not refer to style dictionary: bounds, frame.

Warning: If you modify the Style Dictionary or any of its ancestors, the value of the CALayer property is undefined until the style property is reset.

When it is not nil, dictionary dereferences to look for property values not explicitly defined by CALayer. (This dictionary may in turn have the style attribute, forming a hierarchy of default values.) If the Style Dictionary does not define a value for the attribute, the + defaultValueForKey: method is called. Defaults to nil.

allowsEdgeAntialiasing

A Boolean value indicating whether the CALayer is allowed to perform edge antialiasing.

@property BOOL allowsEdgeAntialiasing API_AVAILABLE(macos(10.10), ios(2.0), watchos(2.0), tvos(9.0));
Copy the code

A value of YES allows CALayer to anti-aliasing its edges as required by the value in its edgeAntialiasingMask property. The default value is read from the Boolean UIViewEdgeAntialiasing property in the info.plist file of the main bundle. If NO value is found, the default value is NO.

allowsGroupOpacity

A Boolean value indicating whether the CALayer is allowed to combine itself and its parent into a group.

@property BOOL allowsGroupOpacity API_AVAILABLE(macos(10.10), ios(2.0), watchos(2.0), tvos(9.0));
Copy the code

When the value is YES and the value of CALayer’s opacity property is less than 1.0, CALayer is allowed to combine itself into a group separate from its parent. When a CALayer contains multiple opaque components, this gives correct results, but may degrade performance.

The default value is read from the Boolean UIViewGroupOpacity property in the main bundle’s info.plist file. If NO value is found, the default value is YES for apps linked to the iOS 7 SDK or later, and NO for apps linked to earlier SDKS.

Layer Filters

filters

A set of Core Image filters that can be applied to CALayer and its Sublayers content. Animatable.

@property(nullable, copy) NSArray *filters;
Copy the code

The filters you add to this property affect the content of the CALayer, including its border, padded background, and sublayers. The default value for this property is nil.

Changing the input of a CIFilter object directly after it is attached to a CALayer results in undefined behavior. Filter parameters can be modified after attaching the filter to CALayer, but this must be done using the layer’s setValue:forKeyPath: method. In addition, you must give the filter a name to identify it in the array. For example, to change the inputRadius parameter of the filter, you can use code similar to the following:

CIFilter *filter = ... ; CALayer *layer = ... ; filter.name = @"myFilter";
layer.filters = [NSArray arrayWithObject:filter];
[layer setValue:[NSNumber numberWithInt:1] forKeyPath:@"filters.myFilter.inputRadius"];
Copy the code

Layers in iOS do not support this property.

compositingFilter

A Core Image filter for synthesizing CALayer and the content behind it. Animatable.

@property(nullable, strong) id compositingFilter;
Copy the code

The default value for this property is nil, which causes layers to be composited using source overlays. Although you can take any Core Image filters used for synthetic filter layer, but for best results, please use the CICategoryCompositeOperation category filter.

In macOS, you can modify the filter parameters after attaching it to a layer, but you must use the layer’s setValue:forKeyPath: method. For example, to change the inputRadius parameter for the filter, you can use code similar to the following:

CIFilter *filter = ... ; CALayer *layer = ... ; layer.compositingFilter = filter; [layer setValue:[NSNumber numberWithInt:1] forKeyPath:@"compositingFilter.inputRadius"];
Copy the code

Changing the input of a CIFilter object directly after it has been attached to the layer results in undefined behavior.

Layers in iOS do not support this property.

backgroundFilters

A set of Core Image filters that can be applied to the content immediately behind the layer. Animatable.

@property(nullable, copy) NSArray *backgroundFilters;
Copy the code

The background filter affects what is displayed behind the layer within the layer itself. Typically, this content belongs to the Superlayer that acts as the parent of the layer. These filters do not affect the content of the layer itself, including the background color and border of the layer.

The default value for this property is nil.

Changing the input of a CIFilter object directly after it has been attached to the layer results in undefined behavior. In macOS, you can modify filter parameters after attaching a filter to a layer, but you must use the layer’s setValue:forKeyPath: method for doing this. In addition, you must give the filter a name to identify it in the array. For example, to change the inputRadius parameter of the filter, you can use code similar to the following:

CIFilter *filter = ... ; CALayer *layer = ... ; filter.name = @"myFilter";
layer.backgroundFilters = [NSArray arrayWithObject:filter];
[layer setValue:[NSNumber numberWithInt:1] forKeyPath:@"backgroundFilters.myFilter.inputRadius"];
Copy the code

You can use layer masksToBounds to control the extent of the background filter effect.

Array of filters applied to the layer background. The root layer ignores this property. Animatable.

minificationFilter

Filters to use when reducing content size.

@property(copy) CALayerContentsFilter minificationFilter;
Copy the code

The possible values for this property are listed in Scaling Filters.

The default value for this property is kCAFilterLinear.

The type of filter to use when rendering CALayer’s contents property. The zoom filter is used to reduce the size of the image data, and the zoom filter is used to increase the size of the image data. Currently allowed values are “nearest” and “Linear”. These two properties default to “Linear”.

minificationFilterBias

Reduce the deviation factor used by the filter to determine the degree of detail.

@property float minificationFilterBias;
Copy the code

When this value is set to kCAFilterTrilinear, the minificationFilter uses this value.

The default value for this property is 0.0.

The bias factor added when determining the level of detail to use when minimizing using trilinear filtering. The default value is 0. Animation can be set.

magnificationFilter

Filter used to increase content size.

@property(copy) CALayerContentsFilter magnificationFilter;
Copy the code

The possible values for this property are listed in Scaling Filters.

The default value for this property is kCAFilterLinear.

Figure 1 shows the difference between linear and nearest filtering when magnifying a 10 x 10 point circle image by 10 times.

Figure 1 Circle with different Magnification filters

Use kCAFilterLinear for the left circle and kCAFilterNearest for the right circle.