在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, pathBounds, minPercent, maxPercent, baselinePointArray, toplinePointArray);
CGPathAddLineToPoint(warpedPath, NULL, warpedPoint.x, warpedPoint.y);
}
else if (element->type == kCGPathElementAddQuadCurveToPoint) {
CGPoint origCtrlPoint = element->points[0];
CGPoint warpedCtrlPoint = warpPoint(origCtrlPoint, pathBounds, minPercent, maxPercent, baselinePointArray, toplinePointArray);
CGPoint origPoint = element->points[1];
CGPoint warpedPoint = warpPoint(origPoint, pathBounds, minPercent, maxPercent, baselinePointArray, toplinePointArray);
CGPathAddQuadCurveToPoint(warpedPath, NULL, warpedCtrlPoint.x, warpedCtrlPoint.y, warpedPoint.x, warpedPoint.y);
}
else if (element->type == kCGPathElementAddCurveToPoint) {
CGPoint origCtrlPoint1 = element->points[0];
CGPoint warpedCtrlPoint1 = warpPoint(origCtrlPoint1, pathBounds, minPercent, maxPercent, baselinePointArray, toplinePointArray);
CGPoint origCtrlPoint2 = element->points[1];
CGPoint warpedCtrlPoint2 = warpPoint(origCtrlPoint2, pathBounds, minPercent, maxPercent, baselinePointArray, toplinePointArray);
CGPoint origPoint = element->points[2];
CGPoint warpedPoint = warpPoint(origPoint, pathBounds, minPercent, maxPercent, baselinePointArray, toplinePointArray);
CGPathAddCurveToPoint(warpedPath, NULL, warpedCtrlPoint1.x, warpedCtrlPoint1.y, warpedCtrlPoint2.x, warpedCtrlPoint2.y, warpedPoint.x, 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, NULL, 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, NULL, 0.f, lengths, 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, NULL, 187.5, 210.f, 187.5, 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, NULL, 170.f, 250.f, 50.f, M_PI, 2 * M_PI, NO);
CGPathAddArc(baselinePath, NULL, 270.f, 250.f, 50.f, M_PI, 2 * M_PI, 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, NULL, 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, NULL, NULL);
CGFloat currentGlyphOffsetPercent = currentOffset/fullWidth;
CGFloat currentGlyphPercentWidth = currentGlyphWidth/fullWidth;
currentOffset += currentGlyphWidth;
CGGlyph glyph;
CGPoint position;
CTRunGetGlyphs(run, glyphRange, &glyph);
CTRunGetPositions(run, glyphRange, &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的部分。 带下行的雕文确实有效,但效果不佳。 有些想法将不得不进入如何处理这些问题。 另外,我的字母间距很宽松。
显然这是一个不平凡的问题。 我相信有更好的方法可以用第三方库来有效地扭曲贝塞尔路径。 然而,为了知道如果没有第三方图书馆可以做到这一点,我认为这表明它可以。
来源:https://developer.apple.com/library/mac/samplecode/CoreTextArcCocoa/Introduction/Intro.html
来源:http://www.planetclegg.com/projects/WarpingTextToSplines.html
来源(让数学更聪明):获得时间路径的位置
链接地址: http://www.djcxy.com/p/79673.html