Detect when a unicode character cannot be displayed correctly

后端 未结 2 871
傲寒
傲寒 2020-12-06 07:42

Some unicode characters cannot be displayed on iOS but are displayed correctly on macOS. Similarly, some unicode characters that iOS can display cannot be displayed on watch

2条回答
  •  不思量自难忘°
    2020-12-06 07:53

    Compare against the known, undefined character U+1FFF:

    /// - Parameter font: a UIFont
    /// - Returns: true if glyph exists
    func glyphAvailable(forFont font:UIFont) -> Bool {
        if let refUnicodePng = Character("\u{1fff}").png(forFont: font),
            let myPng = self.png(forFont: font) {
            return refUnicodePng != myPng
        }
        return false
    }
    

    using a png bitmap:

    /// - Parameter font: a UIFont
    /// - Returns: an optional png representation
    func png(forFont font: UIFont) -> Data? {
        let attributes = [NSAttributedStringKey.font: font]
        let charStr = "\(self)" as NSString
        let size = charStr.size(withAttributes: attributes)
    
        UIGraphicsBeginImageContext(size)
        charStr.draw(at: CGPoint(x: 0,y :0), withAttributes: attributes)
    
        var png:Data? = nil
        if let charImage = UIGraphicsGetImageFromCurrentImageContext() {
            png = UIImagePNGRepresentation(charImage)
        }
    
        UIGraphicsEndImageContext()
        return png
    }
    

    Answered here.

提交回复
热议问题