ios 菜鸟之绘制文本 (真的麻烦)

68 阅读1分钟
class CusView : UIView {
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        //获取ctx
        let ctx = UIGraphicsGetCurrentContext()
        
        ctx?.setCharacterSpacing(10) //设置字间距
        ctx?.setFillColor(UIColor.red.cgColor) //设置填充颜色
        ctx?.setStrokeColor(UIColor.blue.cgColor) //设置线条颜色
        
        ctx?.setTextDrawingMode(.fill)//使用填充模式绘制文本
        
        
        let textPath = CGMutablePath()
        textPath.addRect(rect)
        ctx?.addPath(textPath)
        
        //在UIView中的坐标原点在左上角与CoreText中的坐标原点是在左下角
        ctx?.translateBy(x: 0, y: self.bounds.height)
        ctx?.scaleBy(x: 1, y: -1)

        let str = "我的滑板鞋,时尚时尚最时尚"
        
        //文字样式属性
        let style = NSMutableParagraphStyle()
        style.alignment = .right
        
        //NSAttributedStringKey.font 不能用就用这个 NSFontAttributeName
        let attrString = NSAttributedString(string: str,
                                            attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16),
                                                         NSAttributedString.Key.kern: -0.5,NSAttributedString.Key.foregroundColor: UIColor.white,
                                                         NSAttributedString.Key.paragraphStyle: style])
        let framesetter = CTFramesetterCreateWithAttributedString(attrString)
        let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attrString.length),
                                             textPath, nil)
        //使用CTFrameDraw进行绘制
        CTFrameDraw(frame, ctx!)
    }
}

太麻烦了,有大神知道简单办法 @我 感谢

加油.png