2017-01-23 90 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