在iOS上绘制扭曲的文本

使用iOS 9及更高版本中提供的标准API,如何在绘制文本时实现扭曲效果(如下图所示)?

我怎么想象这可能是有用的,通过指定基本上四个“路径段”,可以是Bézier曲线或直线段(通常可以在CGPath或UIBezierPath中创建的任何单个“元素”)定义四个边缘的形状文本的边界框.

此文本不需要是可选择的.它也可能是一个图像,但我希望找到一种在代码中绘制它的方法,因此我们不必为每个本地化都有单独的图像.我喜欢使用CoreGraphics,Nsstring / NSAttributedString绘图添加,UIKit / TextKit甚至CoreText的答案.我只是决定在使用OpenGL或Metal之前使用图像,但这并不意味着我不会接受一个好的OpenGL或Metal答案,如果它实际上是唯一的方法.

解决方法

只使用CoreText和CoreGraphics即可实现此效果.

我能够使用许多近似技术来实现它.我使用近似(通过CGPathCreatecopyByDashingPath)做的大部分工作,理论上可以用更聪明的数学代替.这可以提高性能并使得结果路径更平滑.

基本上,您可以参数化顶线和基线路径(或接近参数化,就像我所做的那样). (您可以定义一个函数,该函数沿路径获取给定百分比的点.)

CoreText可以将每个字形转换为CGPath.使用一个函数在每个字形路径上运行CGPathApply,该函数将沿路径的每个点映射到沿文本行的匹配百分比.将点映射到水平百分比后,您可以沿着顶线和基线沿该百分比的2个点定义的线进行缩放.根据线的长度与字形的高度来缩放沿该线的点,并创建新的点.将每个缩放点保存到新的CGPath.填写那条路.

我已经在每个字形上使用了CGPathCreatecopyByDashingPath来创建足够的点,我不需要处理数学来曲线化一个长的Lineto元素(例如).这使得数学更简单,但可以使路径看起来有点锯齿状.要解决此问题,您可以将生成的图像传递到平滑过滤器(例如CoreImage),或将路径传递给可以平滑和简化路径的库.

(我原本只是尝试使用CoreImage失真滤镜来解决整个问题,但效果从未产生过正确的效果.)

这是结果(注意使用近似的略微锯齿状边缘):

这里是两行中每一个百分比之间绘制的线条:

这是我如何工作(180行,滚动):

static CGPoint pointAtPercent(CGFloat percent,NSArray<NSValue *> *pointArray) {
    percent = MAX(percent,0.f);
    percent = MIN(percent,1.f);

    int floorIndex = floor(([pointArray count] - 1) * percent);
    int ceilIndex = ceil(([pointArray count] - 1) * percent);

    CGPoint floorPoint = [pointArray[floorIndex] CGPointValue];
    CGPoint ceilPoint = [pointArray[ceilIndex] CGPointValue];

    CGPoint midpoint = CGPointMake((floorPoint.x + ceilPoint.x) / 2.f,(floorPoint.y + ceilPoint.y) / 2.f);

    return midpoint;
}

static void applierSavePoints(void* info,const CGpathelement* element) {
    NSMutableArray *pointArray = (__bridge NSMutableArray*)info;
    // Possible to get higher resolution out of this with more point types,// or by using math to walk the path instead of just saving a bunch of points.
    if (element->type == kCGpathelementMovetoPoint) {
        [pointArray addobject:[NSValue valueWithCGPoint:element->points[0]]];
    }
}

static CGPoint warpPoint(CGPoint origPoint,CGRect pathBounds,CGFloat minPercent,CGFloat maxPercent,NSArray<NSValue*> *baselinePointArray,NSArray<NSValue*> *toplinePointArray) {

    CGFloat mappedPercentWidth = (((origPoint.x - pathBounds.origin.x)/pathBounds.size.width) * (maxPercent-minPercent)) + minPercent;
    CGPoint baselinePoint = pointAtPercent(mappedPercentWidth,baselinePointArray);
    CGPoint toplinePoint = pointAtPercent(mappedPercentWidth,toplinePointArray);

    CGFloat mappedPercentHeight = -origPoint.y/(pathBounds.size.height);

    CGFloat newX = baselinePoint.x + (mappedPercentHeight * (toplinePoint.x - baselinePoint.x));
    CGFloat newY = baselinePoint.y + (mappedPercentHeight * (toplinePoint.y - baselinePoint.y));

    return CGPointMake(newX,newY);
}

static void applierWarpPoints(void* info,const CGpathelement* element) {
    WPWarpInfo *warpInfo = (__bridge WPWarpInfo*) info;

    CGMutablePathRef warpedpath = warpInfo.warpedpath;
    CGRect pathBounds = warpInfo.pathBounds;
    CGFloat minPercent = warpInfo.minPercent;
    CGFloat maxPercent = warpInfo.maxPercent;
    NSArray<NSValue*> *baselinePointArray = warpInfo.baselinePointArray;
    NSArray<NSValue*> *toplinePointArray = warpInfo.toplinePointArray;

    if (element->type == kCGpathelementCloseSubpath) {
        CGPathCloseSubpath(warpedpath);
    }
    // Only allow Moveto at the beginning. Keep everything else connected to remove the dashing.
    else if (element->type == kCGpathelementMovetoPoint && CGPathIsEmpty(warpedpath)) {
        CGPoint origPoint = element->points[0];
        CGPoint warpedPoint = warpPoint(origPoint,pathBounds,minPercent,maxPercent,baselinePointArray,toplinePointArray);
        CGPathMovetoPoint(warpedpath,NULL,warpedPoint.x,warpedPoint.y);
    }
    else if (element->type == kCGpathelementAddLinetoPoint || element->type == kCGpathelementMovetoPoint) {
        CGPoint origPoint = element->points[0];
        CGPoint warpedPoint = warpPoint(origPoint,toplinePointArray);
        CGPathAddLinetoPoint(warpedpath,warpedPoint.y);
    }
    else if (element->type == kCGpathelementAddQuadCurvetoPoint) {
        CGPoint origCtrlPoint = element->points[0];
        CGPoint warpedCtrlPoint = warpPoint(origCtrlPoint,toplinePointArray);
        CGPoint origPoint = element->points[1];
        CGPoint warpedPoint = warpPoint(origPoint,toplinePointArray);
        CGPathAddQuadCurvetoPoint(warpedpath,warpedCtrlPoint.x,warpedCtrlPoint.y,warpedPoint.y);
    }
    else if (element->type == kCGpathelementAddCurvetoPoint) {
        CGPoint origCtrlPoint1 = element->points[0];
        CGPoint warpedCtrlPoint1 = warpPoint(origCtrlPoint1,toplinePointArray);
        CGPoint origCtrlPoint2 = element->points[1];
        CGPoint warpedCtrlPoint2 = warpPoint(origCtrlPoint2,toplinePointArray);
        CGPoint origPoint = element->points[2];
        CGPoint warpedPoint = warpPoint(origPoint,toplinePointArray);
        CGPathAddCurvetoPoint(warpedpath,warpedCtrlPoint1.x,warpedCtrlPoint1.y,warpedCtrlPoint2.x,warpedCtrlPoint2.y,warpedPoint.y);
    }
    else {
        NSLog(@"Error: UnkNown Point Type");
    }
}

- (NSArray<NSValue *> *)pointArrayFromPath:(CGPathRef)path {
    NSMutableArray<NSValue*> *pointArray = [[NSMutableArray alloc] init];
    CGFloat lengths[2] = { 1,0 };
    CGPathRef dashedpath = CGPathCreatecopyByDashingPath(path,0.f,lengths,2);
    CGPathApply(dashedpath,(__bridge void * _Nullable)(pointArray),applierSavePoints);
    CGPathRelease(dashedpath);
    return pointArray;
}

- (CGPathRef)createWarpedpathFromPath:(CGPathRef)origPath withBaseline:(NSArray<NSValue *> *)baseline topLine:(NSArray<NSValue *> *)topLine fromPercent:(CGFloat)startPercent toPercent:(CGFloat)endPercent {
    CGFloat lengths[2] = { 1,0 };
    CGPathRef dashedpath = CGPathCreatecopyByDashingPath(origPath,2);

    // WPWarpInfo is just a class I made to hold some stuff.
    // I needed it to hold some NSArrays,so a struct wouldn't work.
    WPWarpInfo *warpInfo = [[WPWarpInfo alloc] initWithOrigPath:origPath minPercent:startPercent maxPercent:endPercent baselinePointArray:baseline toplinePointArray:topLine];

    CGPathApply(dashedpath,(__bridge void * _Nullable)(warpInfo),applierWarpPoints);
    CGPathRelease(dashedpath);

    return warpInfo.warpedpath;
}

- (void)drawRect:(CGRect)rect {
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGMutablePathRef toplinePath = CGPathCreateMutable();
    CGPathAddArc(toplinePath,187.5,210.f,M_PI,2 * M_PI,NO);
    NSArray<NSValue *> * toplinePoints = [self pointArrayFromPath:toplinePath];
    CGContextAddpath(ctx,toplinePath);
    CGContextSetstrokeColorWithColor(ctx,[UIColor redColor].CGColor);
    CGContextstrokePath(ctx);
    CGPathRelease(toplinePath);

    CGMutablePathRef baselinePath = CGPathCreateMutable();
    CGPathAddArc(baselinePath,170.f,250.f,50.f,NO);
    CGPathAddArc(baselinePath,270.f,YES);
    NSArray<NSValue *> * baselinePoints = [self pointArrayFromPath:baselinePath];
    CGContextAddpath(ctx,baselinePath);
    CGContextSetstrokeColorWithColor(ctx,[UIColor redColor].CGColor);
    CGContextstrokePath(ctx);
    CGPathRelease(baselinePath);


    // Draw 100 of the connecting lines between the strokes.
    /*for (int i = 0; i < 100; i++) {
        CGPoint point1 = pointAtPercent(i * 0.01,toplinePoints);
        CGPoint point2 = pointAtPercent(i * 0.01,baselinePoints);

        CGContextMovetoPoint(ctx,point1.x,point1.y);
        CGContextAddLinetoPoint(ctx,point2.x,point2.y);

        CGContextSetstrokeColorWithColor(ctx,[UIColor blackColor].CGColor);
        CGContextstrokePath(ctx);
    }*/


    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@"WARP"];
    UIFont *font = [UIFont fontWithName:@"Helvetica" size:144];
    [attrString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0,[attrString length])];

    CTLineRef line = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)attrString);
    CFArrayRef runArray = CTLineGetGlyphRuns(line);
    // Just get the first run for this.
    CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runArray,0);
    CTFontRef runFont = CFDictionaryGetValue(CTRunGetAttributes(run),kCTFontAttributeName);
    CGFloat fullWidth = (CGFloat)CTRunGetTypographicBounds(run,CFRangeMake(0,CTRunGetGlyphCount(run)),NULL);
    CGFloat currentOffset = 0.f;

    for (int curGlyph = 0; curGlyph < CTRunGetGlyphCount(run); curGlyph++) {
        CFRange glyphRange = CFRangeMake(curGlyph,1);
        CGFloat currentGlyphWidth = (CGFloat)CTRunGetTypographicBounds(run,glyphRange,NULL);

        CGFloat currentGlyphOffsetPercent = currentOffset/fullWidth;
        CGFloat currentGlyPHPercentWidth = currentGlyphWidth/fullWidth;
        currentOffset += currentGlyphWidth;

        CGGlyph glyph;
        CGPoint position;
        CTRunGetGlyphs(run,&glyph);
        CTRunGetPositions(run,&position);

        CGAffineTransform flipTransform = CGAffineTransformMakeScale(1,-1);

        CGPathRef glyPHPath = CTFontCreatePathForGlyph(runFont,glyph,&flipTransform);
        CGPathRef warpedGylPHPath = [self createWarpedpathFromPath:glyPHPath withBaseline:baselinePoints topLine:toplinePoints fromPercent:currentGlyphOffsetPercent toPercent:currentGlyphOffsetPercent+currentGlyPHPercentWidth];
        CGPathRelease(glyPHPath);

        CGContextAddpath(ctx,warpedGylPHPath);
        CGContextSetFillColorWithColor(ctx,[UIColor blackColor].CGColor);
        CGContextFillPath(ctx);

        CGPathRelease(warpedGylPHPath);
    }

    CFRelease(line);
}

包含的代码也远非“完整”.例如,CoreText的许多部分都是我浏览过的.带有下行器的雕文确实有效,但效果不佳.有些人认为必须考虑如何处理这些问题.另外,我的字母间距很粗糙.

显然,这是一个非常重要的问题.我确信有更好的方法可以使用能够有效扭曲Bezier路径的第三方库.但是,出于智力运动的目的,看看是否可以在没有第三方库的情况下完成,我认为这表明它可以.

资料来源:https://developer.apple.com/library/mac/samplecode/CoreTextArcCocoa/Introduction/Intro.html

资料来源:http://www.planetclegg.com/projects/WarpingTextToSplines.html

来源(使数学更聪明):Get position of path at time

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...