沿着UIBezierPath丢弃“点”,使点的“中心”位于路径上

时间:2017-03-03 09:43:49

标签: ios objective-c uibezierpath cashapelayer

问题陈述:

创建一个半圆形表盘,沿其圆周有点。用户可以平移并rotate此拨号。

react doc for dangerouslySetInnerHTML

方法

  • 创建了UIView
  • 添加了一个半径为UIView高度两倍的圆圈(使用[UIBezierPath bezierPathWithOvalInRect]CAShapeLayer
  • 沿此圆的圆周添加dots(圆形CALayer个对象),使这些圆点的中心位于圆周上。

障碍:

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

enter image description here

代码如下:

@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];
    }
}

1 个答案:

答案 0 :(得分:3)

试试这个:(支持专业'doh'+ facepalm;)

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

<强>解释

您目前正在路径上定位图层的原点。 (删除角半径,你会看到我的意思。)但是,由于你想要路径上图层的中心,你必须分配到.position

请注意,只有将图层的.anchorPoint属性保留为{0.5, 0.5},才会出现这种情况。 有关详细信息,请参阅Core Animation Basics