就像标题一样,我有一些 Objective-c 代码,如何在 Swift3 中使用它们
CGContextSaveGState(context);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, CGRectMake(0, 0, size.width, size.height));
NSMutableAttributedString *attri = [[NSMutableAttributedString alloc]initWithString:_text];
[attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:NSMakeRange(0, _text.length)];
CTFramesetterRef ctFramesetting = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attri);
CTFrameRef ctFrame = CTFramesetterCreateFrame(ctFramesetting, CFRangeMake(0, attri.length), path, NULL);
CTFrameDraw(ctFrame, context);
CFRelease(path);
CFRelease(ctFramesetting);
CFRelease(ctFrame);
Best Answer-推荐答案 strong>
这是一个干净的 Swift 3 版本:
context.saveGState()
context.textMatrix = CGAffineTransform.identity
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
let path = CGMutablePath()
let rect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
path.addRect(rect, transform: .identity)
let attrString = NSMutableAttributedString(string: _text as String)
attrString.addAttribute(NSFontAttributeName,
value: UIFont.systemFont(ofSize: 10.0),
range: NSRange(location: 0,
length: _text.length))
let ctFramesetting = CTFramesetterCreateWithAttributedString(attrString)
let ctFrame = CTFramesetterCreateFrame(ctFramesetting,
CFRangeMake(0, attrString.length),
path,
nil)
CTFrameDraw(ctFrame, context)
我建议您不要使用转换器。
为什么?
使用转换器,您将
- 可能在需要常量的地方使用变量
- 桥接/转换值
- 显式解包选项
- 打破 Swift 风格(这取决于你实际使用的风格,但仍然如此)
- 打破语言惯例
这意味着您将获得需要重构的不稳定/脏代码
关于ios - 如何将以下有关 CGContext 的代码转换为 Swift3,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/43025984/
|