【问题标题】:draw text on CAShapelayer在 CAShapelayer 上绘制文本
【发布时间】:2018-02-01 13:48:23
【问题描述】:

我正在使用 coregraphics 绘制一条线,并且我想使用 core graphics 绘制一些文本。 我的代码如下;

导入 UIKit

class ArrowLineLayer: CAShapeLayer {

    var startingGlyph : CGRect!

    override init() {
        super.init()
        let fontName = "HelveticaNeue-Bold"
        let font = UIFont(name:fontName , size: 15)
        let measurementString = "28 cm" as NSString
        measurementString.draw(at: CGPoint(x:150,y:100), withAttributes: [NSAttributedStringKey.font: font!])

    }

    func drawArrow(frame:CGRect)
    {
        self.frame = frame
        self.lineWidth = 3
        self.strokeColor = UIColor.red.cgColor
        self.lineCap = "round"

        let path = CGMutablePath()
        path.move(to: CGPoint(x:100 , y:100))
        path.addLine(to: CGPoint(x:200 , y:100))
        let radius: CGFloat = 5.0
        let rect = CGRect(x:100 - radius, y: 100 - radius , width: 2 * radius, height: 2 * radius)
        startingGlyph = rect
        path.addPath(UIBezierPath(ovalIn: rect).cgPath)
        self.path = path
    }


    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }


}

然后我初始化这个层并将其添加到主视图层。我可以看到该行,但看不到文本。我不想使用 CATextlayer,因为我想将整个逻辑保存在一个地方。谁能指出我缺少什么?

问候, 尼娜

【问题讨论】:

    标签: swift core-graphics core-text cashapelayer


    【解决方案1】:

    您可以使用NSAttributedString 创建UIBezierPath,然后将此路径附加到您现有的路径中。

    extension UIBezierPath {
    
        convenience init(text: NSAttributedString) {
            let textPath = CGMutablePath()
            let line = CTLineCreateWithAttributedString(text)
    
            let runs = CTLineGetGlyphRuns(line) as! [CTRun]
    
            for run in runs
            {
                let attributes: NSDictionary = CTRunGetAttributes(run)
                let font = attributes[kCTFontAttributeName as String] as! CTFont
    
                let count = CTRunGetGlyphCount(run)
    
                for index in 0 ..< count
                {
                    let range = CFRangeMake(index, 1)
    
                    var glyph = CGGlyph()
                    CTRunGetGlyphs(run, range, &glyph)
    
                    var position = CGPoint()
                    CTRunGetPositions(run, range, &position)
    
                    let letterPath = CTFontCreatePathForGlyph(font, glyph, nil)
                    let transform = CGAffineTransform(translationX: position.x, y: position.y)
    
                    textPath.addPath(letterPath!, transform: transform)
                }
            }
    
            self.init(cgPath: textPath)
        }
    }
    

    【讨论】:

    • 这是我见过的将文本转换为路径(在 iOS 中)的最清晰的解释。做得好! iOS 人员请注意:您需要翻转 y 轴上的字形以使路径不被翻转。将此添加到转换中:.concatenating(CGAffineTransform(scaleX:1.0, y:-1.0))
    猜你喜欢
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多