绘制具有中心对齐的曲线文本:iOS

时间:2016-10-11 18:07:44

标签: ios objective-c core-graphics

这里我想归档一个圆形的文本,中心对齐。

这是我迄今取得的成就

enter image description here

现在,Test1和Test2从路径开始。我想要从路径中心显示。

以下是在路径上绘制文字的代码。

- (void) drawAttributedString: (NSAttributedString *) string
{
    if (!string) return;
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (context == NULL) COMPLAIN_AND_BAIL(@"No context to draw into", nil);
    if (self.elements.count < 2) return;

    // Keep a running tab of how far the glyphs have traveled to
    // be able to calculate the percent along the point path
    float glyphDistance = 0.0f;
    float lineLength = self.pathLength;

    for (int loc = 0; loc < string.length; loc++)
    {
        // Retrieve item
        NSRange range = NSMakeRange(loc, 1);
        NSAttributedString *item = [string attributedSubstringFromRange:range];

        // Start halfway through each glyph
        CGRect bounding = [item boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:0 context:nil];
        glyphDistance += bounding.size.width /2;

        // Find point
        CGPoint slope;
        CGFloat percentConsumed = glyphDistance / lineLength;
        CGPoint targetPoint = [self pointAtPercent:percentConsumed withSlope:&slope];

        // Accommodate the forward progress
        glyphDistance += bounding.size.width / 2;
        if (percentConsumed >= 1.0f) break;

        // Calculate the rotation
        float angle = atan(slope.y / slope.x); //  + M_PI;
        if (slope.x < 0) angle += M_PI; // going left, update the angle

        // Draw the glyph
        PushDraw(^{
            CGContextTranslateCTM(context, targetPoint.x, targetPoint.y);
            CGContextRotateCTM(context, angle);
            CGContextTranslateCTM(context, -bounding.size.width / 2, -item.size.height / 2);
            [item drawAtPoint:CGPointZero];
        });
    }
}

任何帮助将不胜感激。

0 个答案:

没有答案