首页 文章

在圆上设置刻度以保持居中位置

提问于
浏览
9

如何制作圆形动画缩放,但保持圆的中心位置在同一点 . 此代码使圆的中心向下和向右移动,看起来像是在框架的顶部和左侧边界 .

您可以在另一个图层上看到该图层 .

CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, nil, CGRectMake(400, 400, 1000, 1000));

CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
[shapeLayer setPath:path];
[shapeLayer setFrame:[glView frame]];
[shapeLayer setFillColor:[[UIColor blackColor] CGColor]];

[[glView layer] setMask:shapeLayer];

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.0, 0.0, 0)];
animation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)];
animation.repeatCount = 1;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
animation.duration = 3;
[shapeLayer addAnimation:animation forKey:@"transform.scale"];

2 回答

  • 6

    一个图层围绕其锚点进行缩放,默认情况下该图层是图层框架的中心 . 这在Core Animation Programming Guide - Specifying a Layer's Geometry中有解释 .

    您的问题是您的圆圈中心与图层的锚点不在同一点 .

    因此,解决问题的一种方法是将 shapeLayer.anchorPoint 移动到圆圈的中心,如下所示:

    CGRect circleFrame = CGRectMake(400, 400, 1000, 1000);
    CGPoint circleAnchor = CGPointMake(CGRectGetMidX(circleFrame) / CGRectGetMaxX(circleFrame),
        CGRectGetMidY(circleFrame) / CGRectGetMaxY(circleFrame));
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:circleFrame];
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = path.CGPath;
    shapeLayer.anchorPoint = circleAnchor;
    shapeLayer.frame = glView.frame;
    shapeLayer.fillColor = [UIColor blackColor].CGColor;
    
    glView.layer.mask = shapeLayer;
    // and then your animation code
    

    您希望在设置框架之前设置锚点,因为在设置框架后设置锚点将更改框架 .

  • 2

    这些是猜测,目前无法尝试自己:

    • 设置shapeLayer 's frame to glView' s bounds ,而不是 frame ,因为它应该在它所属视图的坐标系中,而不是超视图 .

    • 将shapeLayer的 anchorPoint 设置为0.5,0.5 - 这是CALayer的默认值(意思是图层的中心),但根据您所描述的情况,您的形状图层不是这种情况 - 除非框架/边界事件导致问题 .

相关问题