2017-01-23 108 views
0

我尝试沿笔画旋转文本。用户可以通过触摸创建笔画,然后沿他想要的方向移动手指,然后将笔画缩放到手指所在的位置。我想显示笔画的当前长度和文字显示停留比例,并随着笔画旋转。沿笔画绘制并旋转文本

我认为我不是那么遥远的工作解决方案。目前文字并不总是处于正确的位置,它取决于旋转。我认为上下文翻译有问题,但让我看看我的代码。

这是我的方法绘制文本:

- (void)drawText:(NSString *)text withFrame:(CGRect)rect withFont:(UIFont *)font rotation:(float)radians alignment:(NSTextAlignment)alignment context:(CGContextRef)context { 
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; 
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; 
paragraphStyle.alignment = alignment; 

NSDictionary *attributes = @{ NSFontAttributeName: font, 
           NSParagraphStyleAttributeName: paragraphStyle, 
           NSForegroundColorAttributeName: [UIColor blackColor] }; 

CGContextSaveGState(context); 
CGContextScaleCTM(context, 1.0, 1.0); 
//CGRect textSize = [text boundingRectWithSize:rect.size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil]; 
CGContextTranslateCTM(context, rect.origin.x + (rect.size.width * 0.5), rect.origin.y + (rect.size.height * 0.5)); 
CGContextRotateCTM(context, radians); 
CGContextTranslateCTM(context, -(rect.origin.x + (rect.size.width * 0.5)), -(rect.origin.y + (rect.size.height * 0.5))); 

[[UIColor redColor] set]; 
CGContextFillRect(context, rect); 

[text drawInRect:rect withAttributes:attributes]; 

CGContextRestoreGState(context); 
} 

我这样称呼它:

CGFloat a = shapeToBeDrawn.startPoint.y - shapeToBeDrawn.endPoint.y; 
CGFloat c = shapeToBeDrawn.length; 
CGFloat alpha = -asin(a/c); 

CGRect r = CGRectMake(shapeToBeDrawn.startPoint.x, shapeToBeDrawn.startPoint.y - 30, shapeToBeDrawn.endPoint.x - shapeToBeDrawn.startPoint.x, 20); 
[self drawText:lengthStr withFrame:r withFont:[UIFont fontWithName:@"Helvetica" size:18.0f] rotation:alpha alignment:NSTextAlignmentCenter context:context]; 

有IM计算α角,并通过我想要显示的字符串。还可以为形状框架上方的文本创建框架。

这里一个小视频它的外观现在:

Click

希望有人能帮助我,我的问题是清楚的。谢谢:)

+0

什么一段代码定义位置文本输出? – MBo

+0

上面的“drawText”方法调用的代码。在那里我定义了一个矩形。 – Werewolve

回答

1

要在所有象限正确计算角度,使用atan2功能

alpha = atan2(endPoint.y - startPoint.y, endPoint.x - startPoint.x) 

要定义一个矩形 - 计算起始坐标旋转矩形:

x0 = startPoint.x + Sin(alpha) * 30 
y0 = startPoint.y - Cos(alpha) * 30 
rect.width = shapeToBeDrawn.length 
+0

谢谢,但不会改变任何事情。 – Werewolve

+0

我在视频中看到角度在2,3象限中完全错误 - atan2使用应该纠正这个问题。 – MBo

+0

为什么“30”?增加了两项改进,但没有帮助。文本绘制rect现在被创建:CGRect r = CGRectMake(shapeToBeDrawn.startPoint.x + sin(alpha)* 30,(shapeToBeDrawn.startPoint.y - cos(alpha)* 30) - 30,shapeToBeDrawn.endPoint.x - shapeToBeDrawn.startPoint.x,20); – Werewolve