iOS 动画 —— 钟表

钟表是我们常见的,此处用 CALayer 实现一个钟表的效果。

clock.gif
@interface ClockView : UIView

// 开始
- (void)start;
// 停止
- (void)stop;
// 设置背景图片
- (void)setHourHandImage:(CGImageRef)image;
- (void)setMinuteHandImage:(CGImageRef)image;
- (void)setSecondHandImage:(CGImageRef)image;
- (void)setClockBackgroundImage:(CGImageRef)image;

@end

#import "ClockView.h"

// 长度比率
static const CGFloat kHourHandLengthRate = 0.65f;
static const CGFloat kMinuteHandLengthRate = 0.75f;
static const CGFloat kSecondHandLengthRate = 0.8f;
// 宽度
static const CGFloat kHourHandWidth = 10.f;
static const CGFloat kMinuteHandWidth = 8.f;
static const CGFloat kSecondHandWidth = 4.f;

@interface ClockView () {
    CALayer *_containerLayer;
    CALayer *_hourHand;
    CALayer *_minuteHand;
    CALayer *_secondHand;
    NSTimer *_timer;
}
@end

@implementation ClockView

#pragma mark - init
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        // Layer 初始化
        _containerLayer = [CALayer layer] ;
        _hourHand = [CALayer layer] ;
        _minuteHand = [CALayer layer] ;
        _secondHand = [CALayer layer] ;
        
        // 初始化 Image
        [self setClockBackgroundImage:NULL];
        [self setHourHandImage:NULL];
        [self setMinuteHandImage:NULL];
        [self setSecondHandImage:NULL];
        
        // 增加 All Layer
        [_containerLayer addSublayer:_hourHand];
        [_containerLayer addSublayer:_minuteHand];
        [_containerLayer addSublayer:_secondHand];
        [self.layer addSublayer:_containerLayer];
    }
    return self;
}

#pragma mark - startOrStop
- (void)start {
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateClock) userInfo:nil repeats:YES];
}

- (void)stop {
    [_timer invalidate];
    _timer = nil;
}

#pragma mark - SetImage
- (void)setHourHandImage:(CGImageRef)image {
    if (image != NULL) {
        _hourHand.backgroundColor = [UIColor clearColor].CGColor;
        _hourHand.cornerRadius = 0.f;
    }else{
        _hourHand.backgroundColor = [UIColor blackColor].CGColor;
        _hourHand.cornerRadius = 3.f;
    }
    _hourHand.contents = (__bridge id)image;
}

- (void)setMinuteHandImage:(CGImageRef)image {
    if (image != NULL) {
        _minuteHand.backgroundColor = [UIColor clearColor].CGColor;
        _minuteHand.cornerRadius = 0.f;
    }else{
        _minuteHand.backgroundColor = [UIColor grayColor].CGColor;
        _minuteHand.cornerRadius = 3.f;
    }
    _minuteHand.contents = (__bridge id)image;
}

- (void)setSecondHandImage:(CGImageRef)image {
    if (image != NULL) {
        _secondHand.backgroundColor = [UIColor clearColor].CGColor;
        _secondHand.cornerRadius = 0.f;
    }else{
        _secondHand.backgroundColor = [UIColor whiteColor].CGColor;
        _secondHand.cornerRadius = 3.f;
    }
    _secondHand.contents = (__bridge id)image;
}

- (void)setClockBackgroundImage:(CGImageRef)image {
    if (image != NULL) {
        _containerLayer.backgroundColor = [UIColor clearColor].CGColor;
        _containerLayer.cornerRadius = 0.f;
    }else{
        _containerLayer.backgroundColor = [UIColor lightGrayColor].CGColor;
        _containerLayer.cornerRadius = 3.f;
    }
    _containerLayer.contents = (__bridge id)image;
}

#pragma mark - Private Mehtod
CGFloat Degrees2Radians(CGFloat degrees) { return degrees * M_PI / 180; }

- (void)updateClock {
    // 获取时间
    NSDateComponents *dateComponents =[[NSCalendar currentCalendar] components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:[NSDate date]];    
    NSInteger seconds = [dateComponents second];
    NSInteger minutes = [dateComponents minute];
    NSInteger hours = [dateComponents hour];
    // 区分上午和下午
    if (hours > 12) {
        hours -=12;
    }
    //每次 转动的角度
    CGFloat secAngle = Degrees2Radians(seconds/60.0*360);
    CGFloat minAngle = Degrees2Radians(minutes/60.0*360);
    CGFloat hourAngle = Degrees2Radians(hours/12.0*360) + minAngle/12.0;
    // 改变角度,旋转
    _secondHand.transform = CATransform3DMakeRotation (secAngle+M_PI, 0, 0, 1);
    _minuteHand.transform = CATransform3DMakeRotation (minAngle+M_PI, 0, 0, 1);
    _hourHand.transform = CATransform3DMakeRotation (hourAngle+M_PI, 0, 0, 1);
}


#pragma mark - Overides Layout

- (void) layoutSubviews {
    [super layoutSubviews];
    
    _containerLayer.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    CGFloat length = MIN(self.frame.size.width, self.frame.size.height)/2;
    CGPoint center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
    // 设置中心点
    _hourHand.position = _minuteHand.position = _secondHand.position = center;
    CGFloat tempWidth, tempLength;
    
    // 设置 hourHand Frame
    if (_hourHand.contents == NULL){
        tempWidth = kHourHandWidth;
        tempLength = length * kHourHandLengthRate;
    }else{
        tempWidth = CGImageGetWidth((CGImageRef)_hourHand.contents);
        tempLength = CGImageGetHeight((CGImageRef)_hourHand.contents);
    }
    _hourHand.bounds = CGRectMake(0,0,tempWidth,tempLength);
    
    // 设置 minuteHand Frame
    if (_minuteHand.contents == NULL){
        tempWidth = kMinuteHandWidth;
        tempLength = length * kMinuteHandLengthRate;
    }else{
        tempWidth = CGImageGetWidth((CGImageRef)_minuteHand.contents);
        tempLength = CGImageGetHeight((CGImageRef)_minuteHand.contents);
    }
    _minuteHand.bounds = CGRectMake(0,0,tempWidth,tempLength);
    
    // 设置 secondHand Frame
    if (_secondHand.contents == NULL){
        tempWidth = kSecondHandWidth;
        tempLength = length * kSecondHandLengthRate;
    }else{
        tempWidth = CGImageGetWidth((CGImageRef)_secondHand.contents);
        tempLength = CGImageGetHeight((CGImageRef)_secondHand.contents);
    }
    _secondHand.bounds = CGRectMake(0,0,tempWidth,tempLength);
    
    // 设置 anchorPoint == 注意
    _secondHand.anchorPoint = CGPointMake(0.5,0.0);
    _minuteHand.anchorPoint = CGPointMake(0.5,0.0);
    _hourHand.anchorPoint = CGPointMake(0.5,0.0);
    _containerLayer.anchorPoint = CGPointMake(0.5, 0.5);
}

@end
#import "ViewController.h"
#import "ClockView.h"

@interface ViewController ()

@property (nonatomic, strong) ClockView *clockView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.clockView.center = self.view.center;
    [self.view addSubview:self.clockView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.clockView start];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.clockView stop];
}

- (ClockView *)clockView {
    if (!_clockView) {
        _clockView = [[ClockView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)];
        [_clockView setClockBackgroundImage:[UIImage imageNamed:@"backClock"].CGImage];
        [_clockView setSecondHandImage:[UIImage imageNamed:@"second"].CGImage];
        [_clockView setHourHandImage:[UIImage imageNamed:@"hour"].CGImage];
        [_clockView setMinuteHandImage:[UIImage imageNamed:@"minute"].CGImage];
       
    }
    return _clockView;
}

@end

iOS 动画 —— 钟表_第1张图片
没有放图片的时候

注意点1: CALayer 和 Image 的转换

layer.contents =  (__bridge id)([UIImage imageNamed:@"test"].CGImage)

注意点2: CATransform3DMakeRotation

CATransform3DMakeRotation(CGFloat angle, CGFloat x, CGFloat y, CGFloat z);

第一个参数是旋转角度,后面三个参数形成一个围绕其旋转的向量,起点位置由UIView的center属性标识。

注意点3: anchorPoint

iOS 动画 —— 钟表_第2张图片
anchorPoint

锚点对于此处是很重要的,可以理解它的主要作用就是作为变换的支点或旋转点。具体我们可以阅读下彻底理解position与anchorPoint。

你可能感兴趣的:(iOS 动画 —— 钟表)