ios - 如何将以下有关 CGContext 的代码转换为 Swift3
<p><p>就像标题一样,我有一些 Objective-c 代码,如何在 Swift3 中使用它们</p>
<pre><code>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 = [initWithString:_text];
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);
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>这是一个干净的 <code>Swift 3</code> 版本:</p>
<pre><code>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)
</code></pre>
<p>我建议您<strong>不要使用转换器</strong>。</p>
<p><strong>为什么?</strong>
使用转换器,您将</p>
<ul>
<li>可能在需要常量的地方使用变量</li>
<li>桥接/转换值</li>
<li>显式解包选项</li>
<li>打破 Swift 风格(这取决于你实际使用的风格,但仍然如此)</li>
<li>打破语言惯例</li>
</ul>
<p>这意味着您将获得需要重构的不稳定/脏代码</p></p>
<p style="font-size: 20px;">关于ios - 如何将以下有关 CGContext 的代码转换为 Swift3,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/43025984/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/43025984/
</a>
</p>
页:
[1]