在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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple 最新软件的错误和性能问题。
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只有5%的概率会遇到选择运营商界面且部分必须连接到iTunes才可以激活
一般在接外包的时候, 通常第三方需要安装你的app进行测试(这时候你的app肯定是还没传到app store之前)。
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应用变灰了。那么接下来我们看一下Flutter是如何实现的。Flutter中实现整个App变为灰色在Flutter中实现整个App变为灰色是非常简单的,只需要在最外层的控件上包裹ColorFiltered,用法如下:ColorFiltered(颜色过滤器)看名字就知道是增加颜色滤镜效果的,ColorFiltered( colorFilter:ColorFilter.mode(Colors.grey, BlendMode.
flutter升级/版本切换
(1)在C++11标准时,open函数的文件路径可以传char指针也可以传string指针,而在C++98标准,open函数的文件路径只能传char指针;(2)open函数的第二个参数是打开文件的模式,从函数定义可以看出,如果调用open函数时省略mode模式参数,则默认按照可读可写(ios_base:in | ios_base::out)的方式打开;(3)打开文件时的mode的模式是从内存的角度来定义的,比如:in表示可读,就是从文件读数据往内存读写;out表示可写,就是把内存数据写到文件中;
文章目录方法一:分别将图片和文字置灰UIImage转成灰度图UIColor转成灰度颜色方法二:给App整体添加灰色滤镜参考App页面置灰,本质是将彩色图像转换为灰度图像,本文提供两种方法实现,一种是App整体置灰,一种是单个页面置灰,可结合具体的业务场景使用。方法一:分别将图片和文字置灰一般情况下,App页面的颜色深度是24bit,也就是RGB各8bit;如果算上Alpha通道的话就是32bit,RGBA(或者ARGB)各8bit。灰度图像的颜色深度是8bit,这8bit表示的颜色不是彩色,而是256
领导让调研下黑(灰)白化实现方案,自己调研了两天,根据网上资料,做下记录只是学习过程中的记录,还是写作者牛逼
让学前端不再害怕英语单词(二),通过本文,可以对css,js和es6的单词进行了在逻辑上和联想上的记忆,让初学者更快的上手前端代码
用Python送你一颗跳动的爱心
在uni-app项目中实现人脸识别,既使用uni-app中的live-pusher开启摄像头,创建直播推流。通过快照截取和压缩图片,以base64格式发往后端。
商户APP调用微信提供的SDK调用微信支付模块,商户APP会跳转到微信中完成支付,支付完后跳回到商户APP内,最后展示支付结果。CSDN前端领域优质创作者,资深前端开发工程师,专注前端开发,在CSDN总结工作中遇到的问题或者问题解决方法以及对新技术的分享,欢迎咨询交流,共同学习。),验证通过打开选择支付方式弹窗页面,选择微信支付或者支付宝支付;4.可取消支付,放弃支付会返回会员页面,页面提示支付取消;2.判断支付方式,如果是1,则是微信支付方式。1.判断是否在微信内支付,需要在微信外支付。
Mac命令行修改ipa并重新签名打包
首先在 iOS 设备中打开开发者模式。位于:设置 - 隐私&安全 - 开发者模式(需重启)
一 现象导入MBProgressHUD显示信息时,出现如下异常现象Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_MBProgressHUD", referenced from: objc-class-ref in ViewController.old: symbol(s) not found for architecture x86_64clang: error: linker command failed wit
Profiles >> 加号添加 >> Distribution >> "App Store" >> 选择 2.1 创建的App ID >> 选择绑定 2.3 的发布证书(.cer)>> 输入描述文件名称 >> Generate 生成描述文件 >> Download。Certificates >> 加号添加 >> "App Store and Ad Hoc" >> “Choose File...” >> 选择上一步生成的证书请求文件 >> Continue >> Download。
今天有需求,要实现的功能大致如下:在安卓和ios端实现分享功能可以分享链接,图片,文字,视频,文件,等欢迎大佬多多来给萌新指正,欢迎大家来共同探讨。如果各位看官觉得文章有点点帮助,跪求各位给点个“一键三连”,谢啦~声明:本博文章若非特殊注明皆为原创原文链接。