Werewolve
Werewolve

Reputation: 2538

Draw and rotate Text along a stroke

I try to rotate a text along a stroke. The user can create strokes by touch and move the finger in an direction he wants, the stroke then scales to the point where the finger is. I want to show the current length along the stroke and the text show stay scale and rotate with the stroke.

I think im not so far away from the working solution. Currently the text is not always at the right position, its depends on the rotation. I think there is something wrong with Context Translation, but lets see my code.

This is my method to draw the text:

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

I call it like this:

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

There im calculation the angle alpha and pass the string i want to display. And also create the frame for the text above the frame of the shape.

Here a small video how it looks currently:

Click

Hope someone can help me and my problem is clear. Thanks :)

Upvotes: 0

Views: 229

Answers (1)

MBo
MBo

Reputation: 80297

To calculate angle properly in all quadrants, use atan2 function

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

To define a rect - calculate starting coordinates for rotated rectangle:

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

Upvotes: 1

Related Questions