沿着 UIBezierPath 放置“点”,使得点的“中心”位于路径上

Drop `points` along a UIBezierPath such that `center` of points lies ON the path

问题陈述:

创建一个圆周上有圆点的半圆形刻度盘。用户可以平移 rotate 这个拨号盘。

方法:

障碍物:

这些点是沿着一条路径绘制的,但是这些点的中心不在圆周上。

代码如下:

@property (nonatomic, retain) CAShapeLayer* dialLineLayer;

- (instancetype)initWithCoder:(NSCoder *)aDecoder {

    if (self = [super initWithCoder:aDecoder]) {

        self.dialLineLayer = [CAShapeLayer layer];
        CGRect path = CGRectMake(SCREEN_WIDTH /2 - self.radius, -self.radius, 2 * self.radius, 2 * self.radius);

        [self.dialLineLayer setPath:[[UIBezierPath bezierPathWithOvalInRect:path] CGPath]];
        [self.dialLineLayer setStrokeColor:[[UIColor la_white10Color] CGColor]];
        [self.dialLineLayer setFillColor:[[UIColor clearColor] CGColor]];
        [self.dialLineLayer setLineWidth:3.0f];
        [self.layer addSublayer:self.dialLineLayer];

        [self addDotsOnLineLayer];
    }

    return self;
}

- (CGFloat) radius {

    // View has an aspect ratio constraint of 75:34 (W:H)

    return SCREEN_WIDTH * 34 / 75 - 10; // Circle radius is 10px less that View's height
}

- (CGFloat) circumference {

    return M_2_PI * self.radius; // 2Pi * radius
}

- (void) addDotsOnLineLayer {

    CGPoint dotPoint = CGPointMake(SCREEN_WIDTH /2 - self.radius - self.radius/2, 0);

    for (double t = 0; t < 2*M_PI; t += 0.2) {

        CGFloat dotRadius = arc4random_uniform(10) - arc4random_uniform(3); // Random radius between 3px and 10px

        CALayer* dotLayer = [CALayer layer];
        dotLayer.frame = CGRectMake(dotPoint.x, dotPoint.y, dotRadius, dotRadius);
        dotLayer.cornerRadius = dotRadius / 2;
        dotLayer.masksToBounds = YES;
        dotLayer.backgroundColor = [UIColor greenColor].CGColor;

        dotPoint.x = self.radius * cos(t) + (SCREEN_WIDTH / 2);
        dotPoint.y = self.radius * sin(t) + 0;

        [self.dialLineLayer addSublayer:dotLayer];
    }
}

试试这个:(大括号 'doh' + facepalm ;))

dotLayer.frame = CGRectMake(0, 0, dotRadius, dotRadius);
dotLayer.position = dotPoint;

说明

您目前正在将图层的 原点 定位在路径上。 (去掉角半径,你就会明白我的意思了。)但是,由于你想要路径上层的 center,你必须分配给 .position

请注意,只要您将图层的 .anchorPoint 属性 保留在 {0.5, 0.5},这才是正确的。 有关详细信息,请参阅 Core Animation Basics