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

标签 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];

最佳答案

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

关于iphone - 核心图形-使用中点和角度的线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14557290/

相关文章:

iPhone - 转换为 NSData?

ios - 直接渲染CGImage(而不是UIImage)?

iphone - 离屏渲染层

iphone - 将颜色应用于灰度图像,保留 alpha 值 (iOS/Quartz)

objective-c - 对路径中的变换参数使用 NULL 和 CGAffineTransformIdenity 之间的区别

iphone - 点击覆盖时显示标注

iphone - 为什么我的 Application Delegate 中的类变量没有被实例化?

iphone - CoreData 相当于 sum...group by

iphone - 将 UIImage 转换为字节

ios - 如何将 UIImageView 限制在另一个 View 中?