核心图形 - 使用中点和角度的线条

时间:2013-01-28 07:22:28

标签: iphone core-graphics

我希望可以使用中心点和角度绘制一条线。我需要绘制一条线来与一个圆圈一起移动。但我无法使其工作。我不知道怎么做到这一点!我尝试了下面的代码来按指定的角度旋转线,它没有用。因为我很新,我无法理解我犯错的地方! This is how it looks if I use the below code

- (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];

2 个答案:

答案 0 :(得分:2)

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

(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));

答案 1 :(得分: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)