在iOS上绘制扭曲的文本

在iOS上绘制扭曲的文本,第1张

概述使用iOS 9及更高版本中提供的标准API,如何在绘制文本时实现扭曲效果(如下图所示)? 我怎么想象这可能是有用的,通过指定基本上四个“路径段”,可以是Bézier曲线或直线段(通常可以在CGPath或UIBezierPath中创建的任何单个“元素”)定义四个边缘的形状文本的边界框. 此文本不需要是可选择的.它也可能是一个图像,但我希望找到一种在代码中绘制它的方法,因此我们不必为每个本地化都有单独 使用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上绘制扭曲的文本全部内容,希望文章能够帮你解决在iOS上绘制扭曲的文本所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1100168.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存