以下是實作
1. 首先開啓一個專案
2. 在StoryBoard加入六個Button及一個Switch,來顯示動畫的效果
3. 先加入 QuartzCore Framework
4. 在mainViewController.h註冊一個Layer,另外還有Switch作為開關
#import <UIKit/UIKit.h>#import <QuartzCore/QuartzCore.h>
@interface mainViewController : UIViewController
@property (weak) CALayer *layer;
@property (weak, nonatomic) IBOutlet UISwitch *actionsSwitch;
@end
5. 在mainViewController.m加上Layer的程式碼
#import "mainViewController.h"@interface mainViewController ()
@end
#define ORGINAL_POSITION CGPointMake(500, 300)
#define MOVED_POSITON CGPointMake(300, 500)
@implementation mainViewController
@synthesize layer, actionsSwitch;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
layer = [CALayer layer];
layer.bounds = CGRectMake(0, 0, 200, 200);
layer.position = ORGINAL_POSITION; ///CGPointMake(500, 300);
layer.backgroundColor = [UIColor redColor].CGColor;
layer.borderColor = [UIColor blackColor].CGColor;
layer.opacity = 1.0f;
[self.view.layer addSublayer:layer];
actionsSwitch.on = NO;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)toggleCorner:(id)sender {
[CATransaction setDisableActions:actionsSwitch.on];
layer.cornerRadius = (layer.cornerRadius == 0.0f) ? 30.0f : 0.0f;
}
- (IBAction)toggleColor:(id)sender {
[CATransaction setDisableActions:actionsSwitch.on];
CGColorRef redColor = [UIColor redColor].CGColor, blueColor = [UIColor blueColor].CGColor;
layer.backgroundColor = (layer.backgroundColor == redColor) ? blueColor : redColor;
}
- (IBAction)toggleOpacity:(id)sender {
[CATransaction setDisableActions:actionsSwitch.on];
layer.opacity = (layer.opacity == 1.0f) ? 0.5f : 1.0f;
}
- (IBAction)togglePosition:(id)sender {
[CATransaction setDisableActions:actionsSwitch.on];
layer.position = layer.position.x == 500 ? MOVED_POSITON : ORGINAL_POSITION;
}
- (IBAction)toggleBorders:(id)sender {
[CATransaction setDisableActions:actionsSwitch.on];
layer.borderWidth = (layer.borderWidth == 0.0f) ? 10.0f : 0.0f;
}
- (IBAction)toggleBounds:(id)sender {
[CATransaction setDisableActions:actionsSwitch.on];
if (layer.bounds.size.width == layer.bounds.size.height)
layer.bounds = CGRectMake(layer.bounds.origin.x, layer.bounds.origin.y, layer.bounds.size.width + 100, layer.bounds.size.height);
else
layer.bounds = CGRectMake(layer.bounds.origin.x, layer.bounds.origin.y, layer.bounds.size.width - 100, layer.bounds.size.height);
}
@end
6. 執行結果










沒有留言:
張貼留言