Hayek
Hayek

Reputation: 41

Ruby text/ Furigana in ios

I am currently trying to display some text in Japanese on a UITextView. Is it possible to display the furigana above the kanji (like below) in a manner similar to the < rt> tag in html, without using a web view?

enter image description here

A lot of text processing is involved, therefore I cannot simply use a web view. In iOS8, CTRubyAnnotationRef was added but there is no documentation (I would welcome any example), and I am also concerned with the lack of compatibility with iOS7. I thought that it would be possible to display the furigana above with the use of an NSAttributedString, but couldn't as of yet.

Upvotes: 3

Views: 2891

Answers (3)

arsenius
arsenius

Reputation: 13266

Here's a focused extension for NSMutableAttributedString with some comments. This works for UITextView and UILabel on iOS 16*. scaleToFit: false allows the ruby text to make space for itself if it's wider than the base text.

func addRuby(text: String, at range: NSRange? = nil, sizeFactor: Double = 0.5, scaleToFit: Bool = false, alignment: CTRubyAlignment = .center, overhang: CTRubyOverhang = .auto, position: CTRubyPosition = .before) {
    let range = range ?? .init(location: 0, length: self.length)
    let rubyAttributes: [CFString : Any] = [
        kCTRubyAnnotationSizeFactorAttributeName : sizeFactor as CFNumber,
        kCTRubyAnnotationScaleToFitAttributeName : scaleToFit as CFBoolean,
    ]
    let annotation = CTRubyAnnotationCreateWithAttributes(
        alignment,
        overhang,
        position,
        text as CFString,
        rubyAttributes as CFDictionary
    )
    let attributes = [kCTRubyAnnotationAttributeName as NSAttributedString.Key : annotation]
    self.addAttributes(attributes, range: range)
}

Note, you may want to set UITextView.textContainerInset.top to something larger than the default to avoid having the ruby clipped by the scrollview.

* As long as you're using TextKit 2, i.e. haven't touched UITextView.layoutManager.

enter image description here

Upvotes: 1

Gabriele Quatela
Gabriele Quatela

Reputation: 190

Update Swift 5.1

This solution is an update of preview answers and let you write Asian sentences with Phonetic Guide, using a pattern in the strings.

Let's start from handling string.

these 4 extension let you to inject in a string the ruby annotation.

the function createRuby() check the string a pattern, that it is: |word written in kanji《phonetic guide》.

Examples:

|紅玉《ルビー》

|成功《せいこう》するかどうかは、きみの|努力《どりょく》に|係《かか》る。 and so on.

the important thing is to follow the pattern.

extension String {
// 文字列の範囲
private var stringRange: NSRange {
    return NSMakeRange(0, self.utf16.count)
}

// 特定の正規表現を検索
private func searchRegex(of pattern: String) -> NSTextCheckingResult? {
    do {
        let patternToSearch = try NSRegularExpression(pattern: pattern)
        return patternToSearch.firstMatch(in: self, range: stringRange)
    } catch { return nil }
}

// 特定の正規表現を置換
private func replaceRegex(of pattern: String, with templete: String) -> String {
    do {
        let patternToReplace = try NSRegularExpression(pattern: pattern)
        return patternToReplace.stringByReplacingMatches(in: self, range: stringRange, withTemplate: templete)
    } catch { return self }
}

// ルビを生成
func createRuby() -> NSMutableAttributedString {
    let textWithRuby = self
        // ルビ付文字(「|紅玉《ルビー》」)を特定し文字列を分割
        .replaceRegex(of: "(|.+?《.+?》)", with: ",$1,")
        .components(separatedBy: ",")
        // ルビ付文字のルビを設定
        .map { component -> NSAttributedString in
            // ベース文字(漢字など)とルビをそれぞれ取得
            guard let pair = component.searchRegex(of: "|(.+?)《(.+?)》") else {
                return NSAttributedString(string: component)
            }
            let component = component as NSString
            let baseText = component.substring(with: pair.range(at: 1))
            let rubyText = component.substring(with: pair.range(at: 2))

            // ルビの表示に関する設定
            let rubyAttribute: [CFString: Any] =  [
                kCTRubyAnnotationSizeFactorAttributeName: 0.5,
                kCTForegroundColorAttributeName: UIColor.darkGray
            ]
            let rubyAnnotation = CTRubyAnnotationCreateWithAttributes(
                .auto, .auto, .before, rubyText as CFString, rubyAttribute as CFDictionary
            )


            return NSAttributedString(string: baseText, attributes: [kCTRubyAnnotationAttributeName as NSAttributedString.Key: rubyAnnotation])
        }
        // 分割されていた文字列を結合
        .reduce(NSMutableAttributedString()) { $0.append($1); return $0 }
    return textWithRuby
}
}

Ruby Label: the big problem

As you maybe know, Apple has introduced in iOS 8 the ruby annotation like attribute for the attributedString, and if you did create the the attributed string with ruby annotation and did:

myLabel.attributedText = attributedTextWithRuby

the label did shows perfectly the string without problem.

From iOS 11, Apple unfortunately has removed this feature and, so, if want to show ruby annotation you have override the method draw, to effectively draw the text. To do this, you have to use Core Text to handle the text hand it's lines.

Let's show the code

import UIKit

public enum TextOrientation { //1
    case horizontal
    case vertical
}

class RubyLabel: UILabel {

public var orientation:TextOrientation = .horizontal //2

// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
// ルビを表示
override func draw(_ rect: CGRect) {
    //super.draw(rect) //3


    // context allows you to manipulate the drawing context (i'm setup to draw or bail out)
    guard let context: CGContext = UIGraphicsGetCurrentContext() else {
        return
    }
    guard let string = self.text else { return }
    let attributed = NSMutableAttributedString(attributedString: string.createRuby()) //4

    let path = CGMutablePath()
    switch orientation { //5
        case .horizontal:
        context.textMatrix = CGAffineTransform.identity;
        context.translateBy(x: 0, y: self.bounds.size.height);
        context.scaleBy(x: 1.0, y: -1.0);
        path.addRect(self.bounds)
        attributed.addAttribute(NSAttributedString.Key.verticalGlyphForm, value: false, range: NSMakeRange(0, attributed.length))
        case .vertical:
        context.rotate(by: .pi / 2)
        context.scaleBy(x: 1.0, y: -1.0)
        //context.saveGState()
        //self.transform = CGAffineTransform(rotationAngle: .pi/2)
        path.addRect(CGRect(x: self.bounds.origin.y, y: self.bounds.origin.x, width: self.bounds.height, height: self.bounds.width))
        attributed.addAttribute(NSAttributedString.Key.verticalGlyphForm, value: true, range: NSMakeRange(0, attributed.length))
    }

    attributed.addAttributes([NSAttributedString.Key.font : self.font], range: NSMakeRange(0, attributed.length))

    let frameSetter = CTFramesetterCreateWithAttributedString(attributed)

    let frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0,attributed.length), path, nil)

    // Check need for truncate tail
    //6
    if (CTFrameGetVisibleStringRange(frame).length as Int) < attributed.length {
        // Required truncate
        let linesNS: NSArray  = CTFrameGetLines(frame)
        let linesAO: [AnyObject] = linesNS as [AnyObject]
        var lines: [CTLine] = linesAO as! [CTLine]

        let boundingBoxOfPath = path.boundingBoxOfPath

        let lastCTLine = lines.removeLast() //7

        let truncateString:CFAttributedString = CFAttributedStringCreate(nil, "\u{2026}" as CFString, CTFrameGetFrameAttributes(frame))
        let truncateToken:CTLine = CTLineCreateWithAttributedString(truncateString)

        let lineWidth = CTLineGetTypographicBounds(lastCTLine, nil, nil, nil)
        let tokenWidth = CTLineGetTypographicBounds(truncateToken, nil, nil, nil)
        let widthTruncationBegins = lineWidth - tokenWidth
        if let truncatedLine = CTLineCreateTruncatedLine(lastCTLine, widthTruncationBegins, .end, truncateToken) {
            lines.append(truncatedLine)
        }

        var lineOrigins = Array<CGPoint>(repeating: CGPoint.zero, count: lines.count)
        CTFrameGetLineOrigins(frame, CFRange(location: 0, length: lines.count), &lineOrigins)
        for (index, line) in lines.enumerated() {
            context.textPosition = CGPoint(x: lineOrigins[index].x + boundingBoxOfPath.origin.x, y:lineOrigins[index].y + boundingBoxOfPath.origin.y)
            CTLineDraw(line, context)
        }
    }
    else {
        // Not required truncate
        CTFrameDraw(frame, context)
    }
}

//8
override var intrinsicContentSize: CGSize {
    let baseSize = super.intrinsicContentSize

    return CGSize(width: baseSize.width, height: baseSize.height * 1.0)

}

}

Code explanation:

1- Chinese and japanese text can be written in horizontal and vertical way. This enumeration let you switch in easy way between horizontal and vertical orietantation.

2- public variable with switch orientation text.

3- this method must be commented. the reason is that call it you see two overlapping strings:one without attributes, last your attributed string.

4- here call the method of String class extension in which you create the attributed string with ruby annotation.

5- This switch, rotate if need the context in which draw your text in case you want show vertical text. In fact in this switch you add the attribute NSAttributedString.Key.verticalGlyphForm that in case vertical is true, false otherwise.

6- This 'if' is particular important because, the label, cause we had commented the method 'super.draw()' doesn't know how to manage a long string. without this 'if', the label thinks to have only one line to draw. And so, you still to have a string with '...' like tail. In this 'if' the string is broken in more line and drawing correctly.

7- When you don't give to label some settings, the label knows to have more one line but because it can't calculate what is the showable last piece of string, give error in execution time and the app goes in crash. So be careful. But, don't worry! we talk about the right settings to give it later.

8- this is very important to fit the label to text's size.

How to use the RubyLabel

the use of the label is very simple:

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var rubyLabel: RubyLabel! //1

override func viewDidLoad() {
    super.viewDidLoad()
    setUpLabel()
}

private func setUpLabel() {
    rubyLabel.text = "|成功《せいこう》するかどうかは、きみの|努力《どりょく》に|係《かか》る。|人々《ひとびと》の|生死《せいし》に|係《かか》る。"  //2
    //3
    rubyLabel.textAlignment = .left
    rubyLabel.font = .systemFont(ofSize: 20.0)
    rubyLabel.orientation = .horizontal
    rubyLabel.lineBreakMode = .byCharWrapping
}
}

Code Explanation:

1- connect label to xib if use storyboard or xib file or create label.

2- as I say, the use is very simple: here assign the string with ruby pattern like any other string

3- these setting are the setting to have to set to make work the label. You can set via code or via storyboard/xib

Be careful

if you use storyboard/xib, if you don't put correctly the constraints, the label give you the error at point n° 7.

Result

horizontal String

Vertical string

Works, but not perfect As you can see by screenshot, this label work well but still has some problem.

1- with vertical text the label still in horizontal shape;

2- if the string contains \n to split the string in more lines, the label shows only the number of lines that the string would have had if was without the '\n' character.

I'm working for fix these problem, but your help is appreciated.

Upvotes: 4

Hayek
Hayek

Reputation: 41

In the end I created a function that gets the kanji's position and create labels every time, above the kanji. It's quite dirty but it's the only way to insure a compatibility with iOS7.

However I have to mention the remarkable examples that you can find on GitHub for the CTRubyAnnotationRef nowadays like : http://dev.classmethod.jp/references/ios8-ctrubyannotationref/ and https://github.com/shinjukunian/SimpleFurigana

Good luck to all of you !

Upvotes: 1

Related Questions