弯曲的文字起点

时间:2014-10-26 16:56:20

标签: ios nsstring

我用它来生成弯曲的文字:

    - (UIImage*)createCircularText:(NSString*)text withSize:(CGSize)size andCenter:(CGPoint)center
{        
    UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Light" size:15];

    // Start drawing
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // Retrieve the center and set a radius
    CGFloat r = center.x / 3;

    // Start by adjusting the context origin
    // This affects all subsequent operations
    CGContextTranslateCTM(context, center.x, center.y);

    // Calculate the full extent
    CGFloat fullSize = 0;
    for (int i = 0; i < [text length]; i++)
    {
        NSString *letter = [text substringWithRange:NSMakeRange(i, 1)];
        CGSize letterSize = [letter sizeWithAttributes:@{NSFontAttributeName:font}];
        fullSize += letterSize.width;
    }

    // Initialize the consumed space
    CGFloat consumedSize = 0.0f;

    // Iterate through the alphabet
    for (int i = 0; i < [text length]; i++)
    {
        // Retrieve the letter and measure its display size
        NSString *letter = [text substringWithRange:NSMakeRange(i, 1)];
        CGSize letterSize = [letter sizeWithAttributes:@{NSFontAttributeName:font}];

        // Calculate the current angular offset
        //CGFloat theta = i * (2 * M_PI / ((float)[text length] * 3));

        // Move the pointer forward, calculating the new percentage of travel along the path
        consumedSize += letterSize.width / 2.0f;
        CGFloat percent = consumedSize / fullSize;
        CGFloat theta = (percent * 2 * M_PI) / ((float)[text length] / 4);
        consumedSize += letterSize.width / 2.0f;

        // Encapsulate each stage of the drawing
        CGContextSaveGState(context);

        // Rotate the context
        CGContextRotateCTM(context, theta);

        // Translate up to the edge of the radius and move left by
        // half the letter width. The height translation is negative
        // as this drawing sequence uses the UIKit coordinate system.
        // Transformations that move up go to lower y values.
        CGContextTranslateCTM(context, -letterSize.width / 2, -r);

        // Draw the letter and pop the transform state
        [letter drawAtPoint:CGPointMake(0, 0) withAttributes:@{NSFontAttributeName:font}];
        CGContextRestoreGState(context);
    }

    // Retrieve and return the image
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

我得到了回复:

enter image description here

问题是文本从0°开始但实际上我希望它在左边开始更多,因此字符串的中心是0°。如何做到这一点?

1 个答案:

答案 0 :(得分:1)

两个选项应该有效:

  1. 绘制完所有文本后,旋转上下文的一半使用角度,然后从上下文中获取图像。
  2. 两次通过。第一个只是计算绘制文本所需的角度。第二次通过你现在做的事情。除第二遍外,从每个字母的角度减去所需总角度的一半。