简体   繁体   中英

Get each char (with shape) of font from UIFont or .ttf file

I have not exact idea for it is possible or not and also I did try to find solution for my question but did't get success, that's why I am asking here and hope that I will get solution.

I am developing one drawing related app in which I want to get shape of each font that provided by .ttf file or UIFont .

For Ex.

If I have UIFont/.ttf file such like "OpenSans-Italic" then how can get each "char" with it's shape (here "Italic" shape) of "OpenSans" font? And I want to this in Char or NSString.

=> @[ @"a", @"b", @"c", @"d",..@"A", @"B", @"C", @"D",.....@"1", @"2", @"3"....]; // This is char array only for understanding purpose.

Please suggest me, how can I get this?

Here's a way to do it, borrowing from this post. It iterates through all the possible characters in a NSCharacterSet and finds those that are valid. Right now it's using .URLPathAllowedCharacterSet() but it could use others.

import UIKit

var attributedString = NSMutableAttributedString()
if let font = UIFont(name: "OpenSans-Italic", size: 12) {
  let charset = NSCharacterSet.URLPathAllowedCharacterSet()
  for var plane : UInt32 in 0...16 where charset.hasMemberInPlane(UInt8(plane)) {
    let planeRange = (plane << 16)..<((plane+1) << 16)
    for characterValue in planeRange where charset.longCharacterIsMember(characterValue) {
      let character = String(UnicodeScalar(CFSwapInt32HostToLittle(characterValue)))
      attributedString.appendAttributedString(NSAttributedString(string:character, attributes: [NSFontAttributeName:font]))
    }
  }
}

Is it work if available glyphs are listed in code? If it works, everything seems easy.

I mean add some build phase to parse font file and generate some code including all available chars. I have created a project that provided similar idea IconFont . This project provide UIImage from font file. In develop branch, I add a build phase to parse ttf font file using project PyTTF and add code to TBCityIcon.m . It is easy to modify the python script to generate code of a NSArray that contains all available chars.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM