将String转换为其表示的路径画到屏幕上
关于这个问题,我已经在另一篇blog中有所提及:
不过原有的转换代码使用Obj-C写的,在这里我们尝试将其转换为Swift语言,然后利用它实现一个测试小程序.
首先贴出原来Objc的代码:
- (void) setupTextLayer
{
if (self.pathLayer != nil) {
[self.penLayer removeFromSuperlayer];
[self.pathLayer removeFromSuperlayer];
self.pathLayer = nil;
self.penLayer = nil;
}
// Create path from text
// See: http://www.codeproject.com/KB/iPhone/Glyph.aspx
// License: The Code Project Open License (CPOL) 1.02 http://www.codeproject.com/info/cpol10.aspx
CGMutablePathRef letters = CGPathCreateMutable();
CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica-Bold"), 72.0f, NULL);
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:
(id)font, kCTFontAttributeName,
nil];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"你好,大熊猫侯佩!"
//NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"hello world!"
attributes:attrs];
CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)attrString);
CFArrayRef runArray = CTLineGetGlyphRuns(line);
// for each RUN
for (CFIndex runIndex = 0; runIndex < CFArrayGetCount(runArray); runIndex++)
{
// Get FONT for this run
CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runArray, runIndex);
CTFontRef runFont = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName);
// for each GLYPH in run
for (CFIndex runGlyphIndex = 0; runGlyphIndex < CTRunGetGlyphCount(run); runGlyphIndex++)
{
// get Glyph & Glyph-data
CFRange thisGlyphRange = CFRangeMake(runGlyphIndex, 1);
CGGlyph glyph;
CGPoint position;
CTRunGetGlyphs(run, thisGlyphRange, &glyph);
CTRunGetPositions(run, thisGlyphRange, &position);
// Get PATH of outline
{
CGPathRef letter = CTFontCreatePathForGlyph(runFont, glyph, NULL);
CGAffineTransform t = CGAffineTransformMakeTranslation(position.x, position.y);
CGPathAddPath(letters, &t, letter);
CGPathRelease(letter);
}
}
}
CFRelease(line);
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointZero];
[path appendPath:[UIBezierPath bezierPathWithCGPath:letters]];
CGPathRelease(letters);
CFRelease(font);
CAShapeLayer *pathLayer = [CAShapeLayer layer];
pathLayer.frame = self.animationLayer.bounds;
pathLayer.bounds = CGPathGetBoundingBox(path.CGPath);
//pathLayer.backgroundColor = [[UIColor yellowColor] CGColor];
pathLayer.geometryFlipped = YES;
pathLayer.path = path.CGPath;
pathLayer.strokeColor = [[UIColor blackColor] CGColor];
pathLayer.fillColor = nil;
pathLayer.lineWidth = 5.0f;
//pathLayer.lineJoin = kCALineJoinBevel;
pathLayer.lineJoin = kCALineJoinMiter;
[self.animationLayer addSublayer:pathLayer];
self.pathLayer = pathLayer;
//happy commit
NSLog(@"hello world!!!");
//UIImage *penImage = [UIImage imageNamed:@"noun_project_347_2.png"];
UIImage *penImage = [UIImage imageNamed:@"bee.png"];
CALayer *penLayer = [CALayer layer];
penLayer.contents = (id)penImage.CGImage;
penLayer.anchorPoint = CGPointZero;
penLayer.frame = CGRectMake(0.0f, 0.0f, penImage.size.width/5, penImage.size.height/5);
[pathLayer addSublayer:penLayer];
self.penLayer = penLayer;
}
看起来颇长啊!不过不要太在意,因为我们要用Swift重写的代码只提取其中中间的一部分,这样可以更好的重用.
新建一个项目,基于Swift语言.
在项目中新建一个Swift源代码文件,该文件扩展了String类,我们在其扩展中先写一个帮助方法的存根:
extension String{
func toPath(font:CTFont)->CGPath{
}
}
toPath方法用来实现任意String实例到CGPath路径的转换,在其中添加如下内容:
let letters:CGMutablePathRef = CGPathCreateMutable()
let attrs = [kCTFontAttributeName as String:font]
let attrString:NSAttributedString = NSAttributedString(string: self, attributes: attrs)
let line:CTLine = CTLineCreateWithAttributedString(attrString)
let runArray = CTLineGetGlyphRuns(line)
for runIndex in 0..<CFArrayGetCount(runArray){
let run = CFArrayGetValueAtIndex(runArray, runIndex)
let runb = unsafeBitCast(run, CTRun.self)
//let runFont:CTFont = CFDictionaryGetValue(CTRunGetAttributes(runb), kCTFontAttributeName as String) as! CTFont
let CTFontName = unsafeBitCast(kCTFontAttributeName, UnsafePointer<Void>.self)
let runFontC = CFDictionaryGetValue(CTRunGetAttributes(runb), CTFontName)
let runFont = unsafeBitCast(runFontC, CTFont.self)
//for each GLYPH in run
for runGlyphIndex in 0..<CTRunGetGlyphCount(runb){
//get Glyph & Glyph-data
let glyphRange = CFRange(location: runGlyphIndex, length: 1)
//let glyph:UnsafeMutablePointer<CGGlyph> = UnsafeMutablePointer<CGGlyph>.alloc(1)
//glyph.initialize(0)
var glyph:CGGlyph = 0
let position:UnsafeMutablePointer<CGPoint> = UnsafeMutablePointer<CGPoint>.alloc(1)
position.initialize(CGPoint.zero)
CTRunGetGlyphs(runb, glyphRange, &glyph)
CTRunGetPositions(runb, glyphRange, position)
//Get PATH of outline
//let letter = CTFontCreatePathForGlyph(runFont, glyph.memory, nil)
let letter = CTFontCreatePathForGlyph(runFont, glyph, nil)
var t = CGAffineTransformMakeTranslation(position.memory.x, position.memory.y)
//let tx:UnsafeMutablePointer<CGAffineTransform> = UnsafeMutablePointer<CGAffineTransform>.alloc(1)
//tx.initialize(t)
CGPathAddPath(letters, &t, letter)
//CGPathRelease(letter)
position.destroy()
position.dealloc(1)
}
}
let path = UIBezierPath()
path.moveToPoint(CGPoint.zero)
path.appendPath(UIBezierPath(CGPath: letters))
return path.CGPath
大家可以对照原来的Obj-c版本看一下,大致都是一一对应的,只有少数几个涉及操作C语言数据的地方有修改,大家可以参考我写的另一篇blog:
核心功能有了,下面就好办了!我们想要的是点击屏幕开始显示动画,于是重载如下方法:
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if isAnimating { return }
isAnimating = true
flyerLayer.opacity = 0.8
pathLayer.removeAllAnimations()
flyerLayer.removeAllAnimations()
let strokeAnimation = CABasicAnimation(keyPath: "strokeEnd")
strokeAnimation.duration = 20.0
strokeAnimation.fromValue = 0.0
strokeAnimation.toValue = 1.0
strokeAnimation.delegate = self
pathLayer.addAnimation(strokeAnimation, forKey: nil)
let flyAnimation = CAKeyframeAnimation(keyPath: "position")
flyAnimation.duration = 20.0
flyAnimation.path = pathLayer.path
flyAnimation.calculationMode = kCAAnimationPaced
flyerLayer.addAnimation(flyAnimation, forKey: nil)
}
下面是App实际运行的效果:
将String转换为其表示的路径画到屏幕上的更多相关文章
- C++ 将 std::string 转换为 char*
参考: std::string to char* C++ 将 std::string 转换为 char* 目前没有直接进行转换的方法.必须通过string对象的c_str()方法,获取C-style的 ...
- C#中使用Buffer.BlockCopy()方法将string转换为byte array的方法:
public static void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count); 将指定数目的字 ...
- C++不存在从std::string转换为LPCWSTR的适当函数
LPCWSTR是什么类型呢? 看看如何定义的: typedef const wchar_t* LPCWSTR; 顾名思义就是: LPCWSTR是一个指向unicode编码字符串的32位指针,所指向字符 ...
- string[]转换为int[]
今天碰到一个问题,要把string[]转换为int[],但是又不想使用循环转换,找了好久最后找到了这种方法,特此记录下. string[] input = { "1", " ...
- c#中char、string转换为十六进制byte的浅析
问题引出: string转换为byte(十六进制) static void Main(string[] args) { "; byte[] b = Encoding.Default.GetB ...
- JAVA 利用SimpleDateFormat将String转换为格式化的日期
1. /** * 使用用户格式提取字符串日期 * * @param strDate 日期字符串 * @param pattern 日期格式 * @return */ public static Dat ...
- 【VS开发】ConvertBSTRToString(filename) 不能将string转换为BSTR
环境:win7,x64,vs2008 sp1 把VC 6.0的工程文件用VS2008打开,编译报错: error C2664:"_com_util::ConvertBSTRToString& ...
- (转)第04节:Fabric.js用路径画不规则图形
在Canvas上画方形.圆形.三角形都是很容易的,只要调用fabric对应的方法就可以了,但这些都是规则的图形,如果你想画一个不规则的图形,这时候你可以用fabric.js提供的路径绘图方法.所谓路径 ...
- 有趣html5(两)----使用canvas结合剧本画在画布上的简单图(html5另一个强大)
请珍惜劳动小编成果,这篇文章是原来小编,转载请注明出处. 于html5中能够使用canvas标签在画布上绘图,先直接上代码,这篇文章先简介一下canvas的用法.简单画几个圆,矩形,三角形,写字. 在 ...
随机推荐
- mv&cp
mv [选项] [源] [目标] 当目标不存在时,重命名源为目标 当目标存在时,若目标为目录文件,将源移动到目标文件里: 若目标为非目录文件,将源重命名为目标,并强制覆盖目标. mv -b 1 2 ...
- Redis常用命令--SortedSet
SortedSet是一个类似于Set的集合数据类型,里面的每个字符串元素都关联到一个score(整数或浮点数),并且总是通过score来进行排序着. 并且可以取得一定范围内的元素. 在Redis中大概 ...
- SpringMVC 教程 - Controller
原文地址:https://www.codemore.top/cates/Backend/post/2018-04-10/spring-mvc-controller 声明Controller Contr ...
- [HNOI 2010]Bus 公交线路
Description 题库链接 有 \(N\) 个车站, \(K\) 条公交线路.第 \(1\) 到 \(K\) 站是这 \(K\) 线路的起点站.第 \(N-K+1\) 到 \(N\) 是终点站. ...
- [NOIp 2016]换教室
Description 对于刚上大学的牛牛来说,他面临的第一个问题是如何根据实际情况申请合适的课程. 在可以选择的课程中,有 $2n$ 节课程安排在 $n$ 个时间段上.在第 $i$($1 \leq ...
- ●BZOJ 1767 [Ceoi2009]harbingers
题链: http://www.lydsy.com/JudgeOnline/problem.php?id=1767 题解: 斜率优化DP,单调栈,二分 定义 DP[i] 表示从 i 节点出发,到达根所花 ...
- THUWC逛街记
1/28 这次打算去THUWC划个水,就定了1/29中午的飞机.同校有几个同学去PKUWC,求稳搭今天的飞机.中午时候听说今天飞长沙的飞机全都取消了,明天有没有也不好说( 事实证明29号有飞机:( ) ...
- hdu 5468(莫比乌斯+搜索)
hdu 5468 Puzzled Elena /*快速通道*/ Sample Input 5 1 2 1 3 2 4 2 5 6 2 3 4 5 Sample Output Case #1: ...
- hdu 3473 划分树
Minimum Sum Time Limit: 16000/8000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Tot ...
- ⏰Day.js 2kB超轻量时间库 和Moment.js一样的API
Moment.js 是一个大而全的 JS 时间库,很大地方便了我们处理日期和时间.但是 Moment.js太重了(200k+ with locals),可能一般项目也只使用到了她几个常用的API.虽然 ...