2

我希望可以使用中心点和角度画一条线。我需要画线才能沿着圆圈移动。但我无法让它工作。我不知道怎么能做到这一点!我尝试使用以下代码将线条旋转指定角度,但它不起作用。因为我还很新,所以我不明白我在哪里犯错了!!如果我使用下面的代码,这就是它的样子

- (void)drawThumbAtPoint:(CGPoint)sliderButtonCenterPoint inContext:(CGContextRef)context {

//Vertical line
CGPoint newPoint = [self convertPoint:sliderButtonCenterPoint toView:self];
CGFloat angleInRadians = (CGFloat)M_PI/180.0f * currentAngle;
CGFloat distance = 15;
CGPoint point = CGPointMake(newPoint.x + distance * sinf(angleInRadians), newPoint.y + distance * cosf(angleInRadians));

UIGraphicsPushContext(context);
CGContextBeginPath(context);
UIBezierPath *path = [UIBezierPath bezierPath];
path.lineWidth = 10.f;
[path moveToPoint:sliderButtonCenterPoint];
[path addLineToPoint:point];
[[UIColor redColor] set];
[path stroke];
//  CGAffineTransform rot = CGAffineTransformMakeRotation(angleInRadians);
//  [path applyTransform:rot];
UIGraphicsPopContext();
}

和,

CGPoint thumbCenterPoint = CGContextGetPathCurrentPoint(context);
[self drawThumbAtPoint:thumbCenterPoint inContext:context];
4

2 回答 2

2

alpha与x 轴成角度的单位向量是

(cos(alpha), sin(alpha))

现在你要画一条与圆线相切的线,所以它垂直于从圆心到圆线上的点的线。

要获得垂直向量,请将 90º = π/2 添加到角度:

(cos(alpha + π/2), sin(alpha + π/2)) = (-sin(alpha), cos(alpha))

使用基本的三角恒等式。

这(希望)解释了为什么必须将线的端点计算为

CGPointMake(newPoint.x - distance * sinf(angleInRadians), newPoint.y + distance * cosf(angleInRadians));
于 2013-01-28T15:21:18.927 回答
0

这是Swift 4.1中的类似解决方案:

    // adding progress line view:
    // progress: 360 circle degree <=> 100% progress 
    let currentAngle: CGFloat = (progress * 360 / 100) - 90
    let angleInRadians: CGFloat = currentAngle * CGFloat.pi / 180

    let radius: CGFloat = outerCircle.frame.width / 2 - 1.0
    let lineXPosition = outerCircle.center.x + radius * cos(angleInRadians)
    let lineYPosition = outerCircle.center.y + radius * sin(angleInRadians)

    let progressLineView = UIView(frame: .init(x: lineXPosition, y: lineYPosition, width: 1, height: 1))
    progressLineView.backgroundColor = .clear
    progressLineView.transform = CGAffineTransform(rotationAngle: (progress * 360 / 100) * CGFloat.pi / 180)
    progressLineView.layer.cornerRadius = 1.0

    let progressLineSubView = UIView(frame: .zero)
    progressLineSubView.translatesAutoresizingMaskIntoConstraints = false
    progressLineSubView.backgroundColor = .blue
    progressLineSubView.layer.allowsEdgeAntialiasing = true
    progressLineSubView.layer.cornerRadius = 1.0
    progressLineView.addSubview(progressLineSubView)
    NSLayoutConstraint.activate([
        progressLineSubView.centerXAnchor.constraint(equalTo: progressLineView.centerXAnchor),
        progressLineSubView.centerYAnchor.constraint(equalTo: progressLineView.centerYAnchor),
        progressLineSubView.widthAnchor.constraint(equalToConstant: 2.0),
        progressLineSubView.heightAnchor.constraint(equalToConstant: 8.0)
        ])
    addSubview(progressLineView)
于 2019-02-28T14:46:05.093 回答