CALayer anchorPoint 锚点始终为(0,0)

时间:2022-05-10 00:02:02

objc.io 学习 摘自原处修改

对层的属性详细了解可见这里

@interface ClockFace : CAShapeLayer
@property (nonatomic, strong) NSDate *time;
@end

@interface ClockFace ()
@property (nonatomic, strong) CAShapeLayer *hourHand;
@property (nonatomic, strong) CAShapeLayer *minuteHand;
@end

@implementation ClockFace
- (instancetype)init {
    if (self = [super init]) {
        self.backgroundColor = [UIColor grayColor].CGColor;
        self.bounds = CGRectMake(0, 0, 200, 200);
        self.position = CGPointMake(520, 150);
        self.path = [UIBezierPath bezierPathWithOvalInRect:self.bounds].CGPath;
//        self.anchorPoint = CGPointMake(0, 0);
        self.fillColor = [UIColor whiteColor].CGColor;
        self.strokeColor = [UIColor blackColor].CGColor;
        self.lineWidth = 4;
        
        self.hourHand = [CAShapeLayer layer];
        self.hourHand.bounds = CGRectMake(0, 0, 4, 70);//若未设置bounds,anchorPoint实际指向始终为{0,0}代表左上角;默认为{0.5,0.5}代表中心点随着position属性偏移
        self.hourHand.path = [UIBezierPath bezierPathWithRect:self.hourHand.bounds].CGPath;
        self.hourHand.lineWidth = .5f;
        self.hourHand.strokeColor = [UIColor blackColor].CGColor;
        self.hourHand.fillColor = [UIColor yellowColor].CGColor;
        self.hourHand.anchorPoint = CGPointMake(1, 1);
        self.hourHand.position = CGPointMake(102, 100);
        [self addSublayer:self.hourHand];
        
        self.minuteHand = [CAShapeLayer layer];
        self.minuteHand.bounds = CGRectMake(0, 0, 2, 90);
        self.minuteHand.path = [UIBezierPath bezierPathWithRect:self.minuteHand.bounds].CGPath;
        self.minuteHand.lineWidth = .5f;
        self.minuteHand.strokeColor = [UIColor blackColor].CGColor;
        self.minuteHand.fillColor = [UIColor yellowColor].CGColor;
        self.minuteHand.anchorPoint = CGPointMake(1, 1);
        self.minuteHand.position = CGPointMake(101, 100);
        [self addSublayer:self.minuteHand];
    }
    return self;
}

- (void)setTime:(NSDate *)time {
    _time = time;
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [calendar components:NSCalendarUnitHour | NSCalendarUnitMinute fromDate:time];
    self.hourHand.affineTransform = CGAffineTransformMakeRotation(components.hour / 12.0 * 2.0 * M_PI);
    self.minuteHand.affineTransform = CGAffineTransformMakeRotation(components.minute / 60.0 * 2.0 * M_PI);
}

CALayer anchorPoint 锚点始终为(0,0)