Swift | 實現(xiàn)一種簡單的垂直文本渲染

源碼

https://github.com/BackWorld/VerticalLabel

前言

一般來說,UIKit自帶的UILabel只支持水平方向的文本展示(可以RTL),但無法實現(xiàn)垂直方向文本的顯示,要想實現(xiàn)豎排文本的展示,則只能手動實現(xiàn)計算、渲染邏輯。

效果

豎屏
橫屏

參考思路

  1. 可直接通過CoreTextKit去計算frame、繪制;
  2. 可計算每個字符的frame,用CoreGraphics繪制(此處采用);
  3. 可計算每個字符的frame,添加多個UILabel顯示(subviews太多性能太差,不推薦);

實現(xiàn)

關(guān)于上述CoreTextKit繪制的方式,網(wǎng)上已有現(xiàn)成的可以作參考,但個人覺得邏輯過于復(fù)雜,不便理解和靈活修改。

字符size計算

將一段String文本計算每個字符的size,然后通過total widthtotal height來確定要繪制文本的區(qū)域大小。

  1. 計算單個字符的size:
for char in string {
  let size = labelFittedSize(with: .init(char))
}

Character的擴展方法,通過UILabelsizeThatFits(:_)來計算,這樣的好處是可以動態(tài)設(shè)置label的各種屬性,然后獲取label的attributtedString,用于存儲渲染:

定義一個全局drawLabel(工具對象)

private lazy var tmpLabel: UILabel = {
        let lb = UILabel()
        lb.font = font
        lb.text = text
        lb.textAlignment = .center
        lb.numberOfLines = 0
        return lb
    }()
// 每次調(diào)用,都設(shè)置一下font,color
    private var drawLabel: UILabel {
        tmpLabel.font = font
        tmpLabel.textColor = textColor
        return tmpLabel
    }

重新設(shè)置段落高度屬性

func setLabelAttrText(_ text: String) {
        drawLabel.text = text
        guard let attrText = drawLabel.attributedText else {
            return
        }
        var range = NSMakeRange(0, text.count)
        var attrs = attrText.attributes(at: 0, effectiveRange: &range)
        if let pg = attrs[.paragraphStyle] as? NSParagraphStyle,
           let mpg = pg.mutableCopy() as? NSMutableParagraphStyle {
            mpg.lineHeightMultiple = wordSpacing
            attrs[.paragraphStyle] = mpg
        }
        drawLabel.attributedText = NSAttributedString(string: text, attributes: attrs)
    }

計算size,drawLabel為全局屬性

func labelFittedSize(with text: String) -> CGSize {
        setLabelAttrText(text)
        let flexibleSize = CGSize(width: .zero, height: .max)
        return drawLabel.sizeThatFits(flexibleSize)
    }
  1. 計算指定contentSize內(nèi),一豎行(列)的字符

定義幾個數(shù)據(jù)模型:

  class Texter {
        var lines: [Line] = []
        
        class Line: CustomStringConvertible {
            var words: [Word]
            var maxWidth: CGFloat
            
            var height: CGFloat {
                return words.reduce(0){ $0 + $1.size.height }
            }
            
            init(words: [Word], maxWidth: CGFloat) {
                self.words = words
                self.maxWidth = maxWidth
            }
            
            var description: String {
                return "{words: \(words)}, {maxWidth: \(maxWidth)}"
            }
        }
        
        class Word: CustomStringConvertible {
            var text: NSAttributedString
            var size: CGSize
            
            init(text: NSAttributedString, size: CGSize) {
                self.text = text
                self.size = size
            }
            
            var description: String {
                return "{text: \(text.string)}, {size: \(size)}"
            }
        }
    }
    
// 渲染字符用
    class Character: CustomStringConvertible {
        var text: NSAttributedString
        var frame: CGRect
        init(text: NSAttributedString, frame: CGRect) {
            self.text = text
            self.frame = frame
        }
        var description: String {
            return "{text: \(text)}, frame: {\(frame)}"
        }
    }

核心計算方法:


    func calculating() {
        guard let text = text else {
            return
        }
        texter = .init()
        var y = CGFloat.zero
        var x = CGFloat.zero
        var maxW = CGFloat.zero
        
        var words: [Texter.Word] = []
        var isChangedLine = false
        func resetValues() {
            y = 0
            maxW = 0
            words = []
            isChangedLine = true
        }
        
        func addNewLineIfNeeded() -> Bool {
            x += (maxW + lineSpacing)
            if x > contentSize.width {
                if  breaking == .truncate,
                    let words = texter.lines.last?.words,
                    words.count >= 3
                {
                    let size = labelFittedSize(with: ".")
                    let text = drawLabel.attributedText!
                    words[words.count-3..<words.count].forEach{
                        $0.text = text
                        $0.size = size
                    }
                    texter.lines.last?.words = words
                }
                return false
            }
            texter.lines.append(.init(words: words, maxWidth: maxW))
            if limitedLines > 0, texter.lines.count == limitedLines {
                return false
            }
            return true
        }
        func addWord(size: CGSize){
            words.append(.init(text: drawLabel.attributedText!, size: size))
        }
        
        for (i,char) in text.enumerated()
        {
            isChangedLine = false
            if char.isNewline {
                if !addNewLineIfNeeded() {
                    break
                }
                resetValues()
                continue
            }
            
            let str = String(char)
            let size = labelFittedSize(with: str)
            if maxW < size.width {
                maxW = size.width
            }
            
            y += size.height
            if y > contentSize.height {
                if !addNewLineIfNeeded() {
                    break
                }
                resetValues()
                addWord(size: size)
            }
            else {
                y -= size.height
                addWord(size: size)
            }
            
            if !isChangedLine, i == text.count-1 {
                if !addNewLineIfNeeded() {
                    break
                }
            }
            
            y += size.height
        }
    }

上述邏輯較為雜糅,簡單來說就是循環(huán)計算每個字符的size,然后累加size.height,如果>contentSize.height,則創(chuàng)建一個Line(words:[])對象,并加到texter.lines里,否則用words臨時變量存儲一個Word對象,直到i == text.count-1

上述同時對指定行數(shù)的算法、截斷的需求做了處理:

enum BreakingMode: Int {
        case truncate
        case wordWrap
    }

核心計算

func addNewLineIfNeeded() -> Bool {
            x += (maxW + lineSpacing)

// 自動截斷處理:
            if x > contentSize.width {
                if  breaking == .truncate,
                    let words = texter.lines.last?.words,
                    words.count >= 3
                {
                    let size = labelFittedSize(with: ".")
                    let text = drawLabel.attributedText!
                    words[words.count-3..<words.count].forEach{
                        $0.text = text
                        $0.size = size
                    }
                    texter.lines.last?.words = words
                }
                return false
            }

            texter.lines.append(.init(words: words, maxWidth: maxW))

// 行數(shù)限制處理:
            if limitedLines > 0, texter.lines.count == limitedLines {
                return false
            }
            return true
        }
  1. 計算layoutArea

對上述計算得到的texter里的lines.wordssize進(jìn)行計算,得到一個可以容納下所有符合要求的字符的渲染區(qū)域(CGRect):

var textsArea: CGRect {
        let lines = texter.lines
        let w = lines.reduce(0){ $0 + $1.maxWidth + lineSpacing } - lineSpacing
        let heights = lines.map{ $0.height }
        guard
            let h = heights.max(by: { $0 <= $1 }) else {
            return .zero
        }
        return .init(origin: .zero, size: .init(width: w, height: h))
    }
  1. 渲染文本

這里采用了一個TextsView的單獨類來承擔(dān)字符的渲染,目的是為了方便布局對齊。

這里擴展了一個characters數(shù)組計算屬性,將上述的texter中的數(shù)據(jù)轉(zhuǎn)換成直接可以渲染的text、frame對象。該計算也參考了用戶設(shè)置的行對齊的屬性:

enum LineAlignment: Int {
        case top
        case center
        case bottom
    }

核心計算邏輯

    var characters: [Character] {
        guard let firstLine = texter.lines.first else {
            return []
        }
        var x: CGFloat = isLTR ? 0 : (textsArea.maxX - firstLine.maxWidth)
        var yBase: CGFloat = 0
        var y: CGFloat = 0
        
        let area = textsArea
        
        var list: [Character] = []
        
        for line in texter.lines {
// 根據(jù)垂直行對齊的方式,設(shè)置y的base參考線值
            switch lineAlignment {
            case .top: yBase = 0
            case .center: yBase = (area.height - line.height) / 2
            case .bottom: yBase = area.height - line.height
            }
            y = yBase

            for word in line.words {
                list.append(.init(text: word.text, frame: .init(origin: .init(x: x, y: y), size: word.size)))
                y += word.size.height
            }
            if isLTR {
                x += (line.maxWidth + lineSpacing)
            }
            else {
                x -= (line.maxWidth + lineSpacing)
            }
        }
        
        return list
    }

字符渲染:

class TextsView: UIView {
        var characters: [Character] = [] {
            didSet{
                setNeedsDisplay()
            }
        }
        override func draw(_ rect: CGRect) {
            super.draw(rect)
            
            for c in characters {
                c.text.draw(in: c.frame)
            }
        }
    }

// 存儲屬性
private lazy var textsView: TextsView = {
        let view = TextsView()
        addSubview(view)
        return view
    }()

// 賦值,觸發(fā)渲染
textsView.characters = characters
  1. 計算TextsViewframe
      var area = textsArea
        
        switch (xPosition, yPosition) {
        case (.left, .top):
            area.origin = .zero
        case (.left, .center):
            area.origin.y = (contentSize.height - area.size.height)/2
        case (.left, .bottom):
            area.origin.y = contentSize.height - area.size.height
            
        case (.right, .top):
            area.origin.x = contentSize.width - area.size.width
        case (.right, .center):
            area.origin.x = contentSize.width - area.size.width
            area.origin.y = (contentSize.height - area.size.height)/2
        case (.right, .bottom):
            area.origin.x = contentSize.width - area.size.width
            area.origin.y = contentSize.height - area.size.height
            
        case (.center, .top):
            area.origin.x = (contentSize.width - area.size.width) / 2
        case (.center, .center):
            area.origin.x = (contentSize.width - area.size.width) / 2
            area.origin.y = (contentSize.height - area.size.height)/2
        case (.center, .bottom):
            area.origin.x = (contentSize.width - area.size.width) / 2
            area.origin.y = contentSize.height - area.size.height
        }
        textsView.backgroundColor = .clear
        textsView.frame = area

上述frame計算依賴于用戶設(shè)置的水平、垂直方式的對齊方式:

enum XPosition: Int {
        case left
        case center
        case right
    }
    enum YPosition: Int {
        case top
        case center
        case bottom
    }
  1. 外部方法:
func setNeedsUpdate() {
// 計算
        calculating()
// 渲染
        drawingTexts()
    }
}

6. 外部使用:
```swift
@IBOutlet weak var label: VerticalLabel!
    
    @IBAction func xAlignChanged(_ sender: UISegmentedControl) {
        label.horizontal = sender.selectedSegmentIndex
    }
    
    @IBAction func yAlignChanged(_ sender: UISegmentedControl) {
        label.vertical = sender.selectedSegmentIndex
    }
    
    @IBAction func directionChanged(_ sender: UISegmentedControl) {
        label.direction = sender.selectedSegmentIndex
    }
    @IBAction func lineAlignmentChanged(_ sender: UISegmentedControl) {
        label.lineAlign = sender.selectedSegmentIndex
    }

override func viewDidLoad() {
        super.viewDidLoad()
        
        label.font = .boldSystemFont(ofSize: 24)
        label.text = "東風(fēng)夜放花千樹,\n更吹落,星如雨。\n寶馬雕車香滿路,\n鳳簫聲動,玉壺光轉(zhuǎn),\n一夜魚龍舞。\n\n\n\n\n蛾兒雪柳黃金縷,\n笑語盈盈暗香去。\n眾里尋他千百度,\n驀然回首,\n那人卻在,燈火闌珊處。這是超出的文本這是超出的文本這是超出的文本這是超出的文本"
    }

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        label.setNeedsUpdate()
    }

Xib設(shè)置

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,572評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,071評論 3 414
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,409評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,569評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 71,360評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,895評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,979評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,123評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,643評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,559評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,742評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,250評論 5 356
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 43,981評論 3 346
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,363評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,622評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,354評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 47,707評論 2 370

推薦閱讀更多精彩內(nèi)容