Core Animation Programming Guide学习 Part 2

(3)Adopting the CAAction Protocol

The CAAction protocol defines how action objects are invoked. Classes that implement the CAAction protocol have a method with the signature runActionForKey:object:arguments:.

When the action object receives the runActionForKey:object:arguments: message it is passed the action identifier, the layer on which the action should occur, and an optional dictionary of parameters.

Typically, action objects are an instance of a CAAnimation subclass, which implements the CAAction protocol. You can, however, return an instance of any class that implements the protocol. When that instance receives therunActionForKey:object:arguments: message it should respond by performing its action.

When an instance of CAAnimation receives the runActionForKey:object:arguments: message it responds by adding itself to the layer’s animations, causing the animation to run (see Listing 1).

Listing 1  runActionForKey:object:arguments: implementation that initiates an animation

 
- (void)runActionForKey:(NSString *)key
                 object:(id)anObject
              arguments:(NSDictionary *)dict
{
     [(CALayer *)anObject addAnimation:self forKey:key];
}
(4) You can provide a different implied animation for an action identifier by inserting an instance of CAAnimation into theactions dictionary, into an actions dictionary in the style dictionary, by implementing the delegate methodactionForLayer:forKey:, or subclassing a layer class, overriding defaultActionForKey: and returning the appropriate action object.

The example in Listing 2 replaces the default implied animation for the contents property using delegation.

Listing 2  Implied animation for the contents property

 
- (id<CAAction>)actionForLayer:(CALayer *)theLayer
                        forKey:(NSString *)theKey
{
    CATransition *theAnimation=nil;
 
    if ([theKey isEqualToString:@"contents"])
    {
 
        theAnimation = [[CATransition alloc] init];
        theAnimation.duration = 1.0;
        theAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
        theAnimation.type = kCATransitionPush;
        theAnimation.subtype = kCATransitionFromRight;
    }
 
    return theAnimation;
}

The example in Listing 3 disables the default animation for the sublayers property using the actions dictionary pattern.

Listing 3  Implied animation for the sublayers property

// get a mutable version of the current actions dictionary
NSMutableDictionary *customActions=[NSMutableDictionary dictionaryWithDictionary:[theLayer actions]];
 
// add the new action for sublayers
[customActions setObject:[NSNull null] forKey:@"sublayers"];
 
// set theLayer actions to the updated dictionary
theLayer.actions=customActions;
 

(5)Temporarily Disabling Actions

By default, any time you change an animatable property, the appropriate animation will occur.

You can temporarily disable actions when modifying layer properties by using transactions. 


9. Transactions
Every modification to a layer is part of a transaction. CATransaction is the Core Animation class responsible for batching multiple layer-tree modifications into atomic updates to the render tree.

(1)Implicit Transactions

Implicit transactions are created automatically when the layer tree is modified by a thread without an active transaction, and are committed automatically when the thread's run-loop next iterates.

The example in Listing 1 modifies a layer’s opacityzPosition, and position properties, relying on the implicit transaction to ensure that the resulting animations occur at the same time.

Listing 1  Animation using an implicit transaction

theLayer.opacity=0.0;
theLayer.zPosition=-200;
thelayer.position=CGPointMake(0.0,0.0);

Important: When modifying layer properties from threads that don’t have a runloop, you must use explicit transactions.

(2)Explicit Transactions
You create an explicit transaction by sending the CATransaction class a begin message before modifying the layer tree, and a commit message afterwards. Explicit transactions are particularly useful when setting the properties of many layers at the same time (for example, while laying out multiple layers), temporarily disabling layer actions, or temporarily changing the duration of resulting implied animations.

Temporarily Disabling Layer Actions

You can temporarily disable layer actions when changing layer property values by setting the value of the transaction’skCATransactionDisableActions to true. Any changes made during the scope of that transaction will not result in an animation occurring. Listing 2 shows an example that disables the fade animation that occurs when removing aLayerfrom a visible layer-tree.

Listing 2  Temporarily disabling a layer’s actions

[CATransaction begin];
[CATransaction setValue:(id)kCFBooleanTrue
                 forKey:kCATransactionDisableActions];
[aLayer removeFromSuperlayer];
[CATransaction commit];

Overriding the Duration of Implied Animations

You can temporarily alter the duration of animations that run in response to changing layer property values by setting the value of the transaction’s kCATransactionAnimationDuration key to a new duration. Any resulting animations in that transaction scope will use that duration rather than their own. Listing 3 shows an example that causes an animation to occur over 10 seconds rather than the duration specified by the zPosition and opacity animations..

Listing 3  Overriding the animation duration

[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithFloat:10.0f]
                 forKey:kCATransactionAnimationDuration];
theLayer.zPosition=200.0;
theLayer.opacity=0.0;
[CATransaction commit];

Although the above example shows the duration bracketed by an explicit transaction begin and commit, you could omit those and use the implicit transaction instead.

Nesting Transactions

Explicit transactions can be nested, allowing you to disable actions for one part of an animation, or using different durations for the implicit animations of properties that are modified. Only when the outer-most transaction is committed will the animations occur.

Listing 4 shows an example of nesting two transactions. The outer transaction sets the implied animation duration to 2 seconds and sets the layer’s position property. The inner transaction sets the implied animation duration to 5 seconds and changes the layer’s opacity and zPosition.

Listing 4  Nesting explicit transactions

[CATransaction begin]; // outer transaction
 
// change the animation duration to 2 seconds
[CATransaction setValue:[NSNumber numberWithFloat:2.0f]
                forKey:kCATransactionAnimationDuration];
// move the layer to a new position
theLayer.position = CGPointMake(0.0,0.0);
 
[CATransaction begin]; // inner transaction
// change the animation duration to 5 seconds
[CATransaction setValue:[NSNumber numberWithFloat:5.0f]
                 forKey:kCATransactionAnimationDuration];
 
// change the zPosition and opacity
theLayer.zPosition=200.0;
theLayer.opacity=0.0;
 
[CATransaction commit]; // inner transaction
 
[CATransaction commit]; // outer transaction
 
10. Core Animation Extensions for Key-Value Coding
The CAAnimation and CALayer classes extend the NSKeyValueCoding protocol adding default values for keys, expanded wrapping conventions, and key path support for CGPointCGRectCGSize, and CATransform3D.

(1)Key-Value Coding for Compliant Container Classes

Both CALayer and CAAnimation are key-value coding compliant container classes, allowing you to set values for arbitrary keys. That is, while the key “someKey” is not a declared property of the CALayer class, however you can still set a value for the key “someKey” as follows:

[theLayer setValue:[NSNumber numberWithInteger:50] forKey:@"someKey"];
 

You retrieve the value for the key “someKey” using the following code:

someKeyValue=[theLayer valueForKey:@"someKey"];
(2)Default Value Support

Core Animation adds a new convention to key value coding that allows a class to provide a default value that is used when a class has no value set for that key. Both CALayer or CAAnimation support this convention using the class method defaultValueForKey:.

To provide a default value for a key you create a subclass of the class and override defaultValueForKey:. The subclass implementation examines the key parameter and then returns the appropriate default value. Listing 1 shows an example implementation of defaultValueForKey: that provides a new default value for the layer propertymasksToBounds.

Listing 1  Example implementation of defaultValueForKey:

 
+ (id)defaultValueForKey:(NSString *)key
{
    if ([key isEqualToString:@"masksToBounds"])
         return [NSNumber numberWithBool:YES];
 
    return [super defaultValueForKey:key];
}
(3)Wrapping Convensions

When using the key-value coding methods to access properties whose values are not objects the standard key-value coding wrapping conventions support, the following wrapping conventions are used:

C Type

Class

CGPoint

NSValue

CGSize

NSValue

CGRect

NSValue

CGAffineTransform

NSAffineTransform (Mac OS X only)

CATransform3D

NSValue

(4)Key Path Support for Structure Fields

CAAnimation provides support for accessing the fields of selected structures using key paths. This is useful for specifying these structure fields as the key paths for animations, as well as setting and getting values usingsetValue:forKeyPath: and valueForKeyPath:.

CATransform3D exposes the following fields:

Structure Field

Description

rotation.x

The rotation, in radians, in the x axis.

rotation.y

The rotation, in radians, in the y axis.

rotation.z

The rotation, in radians, in the z axis.

rotation

The rotation, in radians, in the z axis. This is identical to setting the rotation.z field.

scale.x

Scale factor for the x axis.

scale.y

Scale factor for the y axis.

scale.z

Scale factor for the z axis.

scale

Average of all three scale factors.

translation.x

Translate in the x axis.

translation.y

Translate in the y axis.

translation.z

Translate in the z axis.

translation

Translate in the x and y axis. Value is an NSSize or CGSize.

CGPoint exposes the following fields:

Structure Field

Description

x

The x component of the point.

y

The y component of the point.

CGSize exposes the following fields:

Structure Field

Description

width

The width component of the size.

height

The height component of the size.

CGRect exposes the following fields:

Structure Field

Description

origin

The origin of the rectangle as a CGPoint.

origin.x

The x component of the rectangle origin.

origin.y

The y component of the rectangle origin.

size

The size of the rectangle as a CGSize.

size.width

The width component of the rectangle size.

size.height

The height component of the rectangle size.

You can not specify a structure field key path using Objective-C 2.0 properties. This will not work:

    myLayer.transform.rotation.x=0;

Instead you must use setValue:forKeyPath: or valueForKeyPath: as shown below:

    [myLayer setValue:[NSNumber numberWithInt:0] forKeyPath:@"transform.rotation.x"];
 
11. Animatable Properties

The following CALayer class properties can be animated by Core Animation. See CALayer for more information.

  • anchorPoint

    Uses the default implied CABasicAnimation described in Table 1.

  • backgroundColor

    Uses the default implied CABasicAnimation described in Table 1. (subproperties are animated using a basic animation)

  • backgroundFilters

    Uses the default implied CATransitionAnimation described in Table 2. Sub-properties of the filters are animated using the default implied CABasicAnimation described in Table 1.

  • borderColor

    Uses the default implied CABasicAnimation described in Table 1.

  • borderWidth

    Uses the default implied CABasicAnimation described in Table 1.

  • bounds

    Uses the default implied CABasicAnimation described in Table 1.

  • compositingFilter

    Uses the default implied CATransitionAnimation described in Table 2. Sub-properties of the filters are animated using the default implied CABasicAnimation described in Table 1.

  • contents

  • contentsRect

    Uses the default implied CABasicAnimation described in Table 1.

  • cornerRadius

    Uses the default implied CABasicAnimation described in Table 1.

  • doubleSided

    No default implied animation is set.

  • filters

    Uses the default implied CABasicAnimation described in Table 1. Sub-properties of the filters are animated using the default implied CABasicAnimation described in Table 1.

  • frame

    The frame property itself is not animatable. You can achieve the same results by modifying the bounds andposition properties instead.

  • hidden

    Uses the default implied CABasicAnimation described in Table 1.

  • mask

    Uses the default implied CABasicAnimation described in Table 1.

  • masksToBounds

    Uses the default implied CABasicAnimation described in Table 1.

  • opacity

    Uses the default implied CABasicAnimation described in Table 1.

  • position

    Uses the default implied CABasicAnimation described in Table 1.

  • shadowColor

    Uses the default implied CABasicAnimation described in Table 1.

  • shadowOffset

    Uses the default implied CABasicAnimation described in Table 1.

  • shadowOpacity

    Uses the default implied CABasicAnimation described in Table 1.

  • shadowRadius

    Uses the default implied CABasicAnimation described in Table 1.

  • sublayers

    Uses the default implied CATransitionAnimation described in Table 2.

  • sublayerTransform

    Uses the default implied CABasicAnimation described in Table 1.

  • transform

    Uses the default implied CABasicAnimation described in Table 1.

  • zPosition

    Uses the default implied CABasicAnimation described in Table 1.

Table 1  Default Implied Basic Animation

Description

Value

Class

CABasicAnimation

duration

.25 seconds, or the duration of the current transaction

keyPath

Dependent on layer property type

Table 2  Default Implied Transition

Description

Value

Class

CATransition

duration

.25 seconds, or the duration of the current transaction

type

Fade (kCATransitionFade)

startProgress

0.0

endProgress

1.0

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值