Core Text

RSS for tag

Create text layouts, optimize font handling, and access font metrics and glyph data using Core Text.

Core Text Documentation

Posts under Core Text tag

27 Posts
Sort by:
Post not yet marked as solved
2 Replies
5.9k Views
I have a String extension function which converts an html string to a NSAttributed string, and it's made up with Swift 3.x. The strings I'm showing in a UILabel consists of different html-tags, like <i>, <b>, and <center>.Using Xcode 9.0.1 and deploying the app with the code onto an iPhone running iOS 10 it's working perfectly.Same app, but deployed to an iPhone running iOS 11, all html-tags are converted - except the <b>.Here's the code: func htmlAttributedString(fontSize: CGFloat = 17.0) -> NSAttributedString? { let fontName = UIFont.systemFont(ofSize: fontSize).fontName let string = self.appending(String(format: "<style>body{font-family: '%@'; font-size:%fpx;}</style>", fontName, fontSize)) guard let data = string.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil } guard let attributedString = try? NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) else { return nil } print("\(String(describing: self)):\(#function): attributedString: \(attributedString)") return attributedString }By looking at the attributedString output to the console, I can see that on the iPhone with iOS 10 the attributed string contains .SFUIText, .SFUIText-Italic, and .SFUIText-BoldItalic as it should, but running iOS 11 the .SFUIText-BoldItalic is missing.Have any one else experienced the same issue, and maybe has come up with a solution?//Mellberg
Posted
by
Post not yet marked as solved
0 Replies
879 Views
The following code allows to create a font with different weights. func makeFont(weight: CGFloat, size: CGFloat) -> UIFont { 		var attributesDict = [String: Any]() 		attributesDict["Weight"] = weight 		/* Rubik-Light - is a variable font */ 		let fontDescriptor = UIFontDescriptor( 				fontAttributes: [ 						UIFontDescriptor.AttributeName.name : "Rubik-Light", 						kCTFontVariationAttribute as UIFontDescriptor.AttributeName : attributesDict 				] 		) 		return UIFont(descriptor: fontDescriptor, size: size) } It works fine on ios 13 and below, but doesn't work on iOS 14. Is there any solution?
Posted
by
Post not yet marked as solved
1 Replies
456 Views
Is there a way to draw the glyph variants out by swiftUI after I get the glyph name or code using core text? I am trying to typesetting math equation using swiftui like what iosMath done in UIlabel. Is there a way to do so?
Posted
by
Post not yet marked as solved
0 Replies
370 Views
iPhones have this innate feature where you can long-press on a word and select look-up to see its definition. Is there a way to store what word is currently being looked-up/which words have been looked-up in the past, using some kind of query/framework?
Posted
by
Post marked as solved
1 Replies
887 Views
Although Text will render two lines if you pass it a 2 line String, it will render the text of both lines concatenated if you pass it as a markdown string. Same if you create an AttributeText before. Examining the AT highlights the markdown structure (NSPresentationIntent, NSInlinePresentationIntent, NSLink, Header, Paragraph, CodeBlock, etc) but this is "flattened" if you will (NSLink works, multiline CodeBlock work). The problem isn't only present in Text. My use case was CoreText 2: I expected that each AttributeText run would be turned into a text layout fragment but NSTextLayoutManager also flattens my example. As an example, a screenshot of a markdown file in Xcode and the rendering in the simulator. 2 "paragraphs" aka 2 text layout fragments. The same test with the EGG recipes rtf file of the CoreText2 WWDC21 session gives predictable results, one text layout fragment per paragraph. I'm wondering if this is a bug or a "feature" of this markdown first iteration? I tried to access the NSPresentationIntent without much luck to populate CoreText2 myself. Any hint would be REALLY welcomed. thank.
Posted
by
Post not yet marked as solved
1 Replies
625 Views
What is the currently recommended way to create a pdf document in Xcode 13 for Mac OSX using Swift and SwiftUI? I find very little documentation on this. Most articles are for IOS. Only some articles for OSX from many, many years back. With SwiftUI, it will become common place for our code to be used interchangeable in multiple operating systems. And pdf is pretty much the way to go with document and report printouts. Please point me in the right direction. Maybe I was just not looking in the right place. My pdf documents are created without any problem for IOS and Ipad using CG and PDFKit functions. But the same code did not work for the Mac app. So I modified the UIFont to NSFont, etc. Context functions are different. Moved to using CoreText for the attributed string placements. ( CTFrame ) But the strange stuff is the Y point placement that is correct for IOS but seems to be reversed for OSX. So this was when I thought I must be using some old stuff that is not meant for today's work. Brief Example below: func pdf_placeText_CT( cgContext: CGContext, pageSize: CGSize, text: String, width: CGFloat, height: CGFloat, font: NSFont, alignment: String, xPoint: CGFloat, yPoint: CGFloat ) {         let pointY = pageSize.height - yPoint  // for some reason we have to flip the vertical. Strange.   let paragraphstyle = NSMutableParagraphStyle()           if ( alignment == "R" ) {       paragraphstyle.alignment = .right     } else if ( alignment == "C" ) {       paragraphstyle.alignment = .center     } else {       paragraphstyle.alignment = .left     }         let attributedText = NSAttributedString(string: text, attributes: [       NSAttributedString.Key.font      : font ,       NSAttributedString.Key.paragraphStyle : paragraphstyle      ])         let stringSize = attributedText.size()   let stringRect = CGRect(x: xPoint, y: pointY, width: stringSize.width+5, height: stringSize.height+5)   let stringPath = CGPath(rect: stringRect, transform: nil)    //attributedText.draw(in: stringRect)       let textFrame = CTFramesetterCreateWithAttributedString(attributedText)   let textRange = CFRangeMake(0, attributedText.length)   var pageRange = CFRange()   CTFramesetterSuggestFrameSizeWithConstraints(textFrame, textRange, nil, pageSize, &pageRange)       let frame = CTFramesetterCreateFrame(textFrame, pageRange, stringPath, nil)       CTFrameDraw(frame, cgContext )      }
Posted
by
Post not yet marked as solved
0 Replies
553 Views
I am using GeometryReader to calculate the size of font to use to fit several lines of text, however it is always too big. What can be wrong with my calculation? Here's a simply Playground import SwiftUI import PlaygroundSupport struct MainView : View { var body: some View { VStack { SomeView() .frame(width: 508.0, height: 246.5) } } } struct SomeView: View { let newData = ["1", "2", "3", "4", "5", "6", "7", "8"] var lines: Int { newData.count } var body: some View { GeometryReader { geometry in VStack(alignment: .leading, spacing: 0) { ForEach(0..<lines) { idx in Text(newData[idx]) .padding(0) } } .font(.system(size: geometry.size.height / CGFloat(lines))) .onAppear { print(geometry.size) print(lines) print(geometry.size.height / CGFloat(lines)) } } } } PlaygroundPage.current.setLiveView(MainView()) This gives me this result which I need to show all 8 lines:  The GeometryReader correctly reports the height of the box to be 246.5 and the number of lines to be 8 which results in a 30.8125 font size. It seems the font size needs some additional padding but how do I calculate this? I want to be able to supply an unknown amount of data and have it fill the box. (Well I am actually using a LazyVGrid which is suffering the same issue).
Posted
by
Post not yet marked as solved
1 Replies
883 Views
I want to use the "SF Pro Text" font in my app. It works fine when I build my app on my main computer running macOS11 Big Sur, but I have a 2nd partition to run macOS Monterey, and it doesn't seem to be available there at all, whether through Interface Builder or through code (using NSFontManager). Using this returns nil on my Monterey partition: NSFont* regularFont = [[NSFontManager sharedFontManager] fontWithFamily:@"SF Pro Text" traits:NSFontWeightRegular weight:5 size: 16.0]; Maybe I'm missing something here ... should I have to install the font manually? I thought the SF Font is a 'system font', so it would be available on all Macs?
Posted
by
Post marked as solved
1 Replies
437 Views
I'm investigating some font/typography issues in a creative application. I am hoping for some information from Apple developers who know how font activation works in Core Text, and how/whether auto-activation is still supported. I'm running on Big Sur in an Obj-C Cocoa app. In applicationDidFinishLaunching the app calls CTFontManagerSetAutoActivationSetting(NULL, kCTFontManagerAutoActivationEnabled); After this, what is the correct API to request auto-activation of a font that may not be active but could be activated, e.g. by a third-party font manager? I have tried using CTFontCreateWithNameAndOptions. For options, I see there is an CTFontOption value kCTFontOptionsPreventAutoActivation - I assume that as long as I don't set this option, the call will attempt auto-activation. However, I don't see any auto-activation resulting, either from the third-party font manager or the OS. Instead CTFontCreateWithNameAndOptions always returns a substitute font (Helvetica). The font I am attempting to auto-activate is an OTF. It is stored in a third-party font manager, and I also have copies of it on the desktop. I have also tried having it present / disabled in FontBook, which also does not auto-activate it in this case. I've also cleaned font caches after making changes. How is the kCTFontManagerAutoActivationEnabled supposed to work in Big Sur? Is there a different Core Text call used to auto-activate a font, or is this behavior no longer supported? Thanks!
Posted
by
Post not yet marked as solved
0 Replies
375 Views
Is there a way to import custom font into Reality composer on iPad? I can see them properly on desktop but I'm trying to figure out how to do the same on Ipad so that when I export my project on the remote device there is visual parity. Thanks
Posted
by
Post not yet marked as solved
0 Replies
251 Views
Dear Support, My query is that I can't install the below fonts in my I-Mac 2020 M1 Chip. please suggest how I can install these below fonts so I complete my tasks timely. IOS in my iMac is Big Sur. Font Name: Ameri BT - family Helvetica - Family Univers - Family
Posted
by
Post not yet marked as solved
0 Replies
343 Views
I have made a Scan to Text app with the help of sources from the internet, but I can’t figure out a way to get my output text to be editable. Here’s my code private func makeScannerView()-> ScannerView {         ScannerView(completion: {             textPerPage in             if let outputText = textPerPage?.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines){                 let newScanData = ScanData(content: outputText)                 self.texts.append(newScanData)             }             self.showScannerSheet = false                      })     }
Posted
by
Post not yet marked as solved
0 Replies
293 Views
In our app we are working with different kinds of documents. When working with text files we can add text attachments, by drag-and-dropping images into UITextView. Those files are saved using NSAttributedString's fileWrapper and proper document type (RTFD for attributed text with attachments) Everything worked fine before updating to macOS Monterey 12.1 But after update fileWrapper function returns the error: "image destination must have at least one image" and results in unknown file icon after saving and loading the file. The issue is caused only when dropping or pasting images (png and jpeg). When working with original RTFD files, created with TextEdit, everything is fine. Seems like it occurs because iOS UIImages cant have tiff representation and RTFD file packages contain tiff images as attachments. Anybody faced this kind of issue? Is this an Apple bug or smth else?
Posted
by
Post not yet marked as solved
0 Replies
269 Views
Here's a simple demo. I run it on macOS 12.1, compiled with Xcode 13.2. struct ContentView: View {     var body: some View {         VStack {             Text("ee")             Text("eé") Text("e\u{E9}") // "e with acute"             Text("ee\u{301}") // "combining acute"         }.font(.custom("Avenir", fixedSize: 18))          .padding(20)     } } In the 4rd one, the "e" is rendered in the wrong size/font. Screenshot: Other fonts do not have the problem. For example, "Avenir Next" and "Helvetica". Is there a way (in code) to tell which fonts can handle combining chars? Is this a bug? I notice the same thing happens when I use Core Text to draw the strings at a low level. So it's not just SwiftUI. In TextEdit, if have Avenir font, type "option-e" + "e" I get a nice letter. Maybe TextEdit is doing what Xcode did in the second line, and using the "e with acute" unicode character.
Posted
by
Post not yet marked as solved
0 Replies
282 Views
Hi, I'm currently looking for a way to render WebVTT subtitles while using AVSampleBufferDisplayLayer. A little background on the issue. In order to comply with some client rules (for play/pause/seek) and support picture in picture, I had to abandon the AVPlayerLayer (switching to AVSampleBufferDisplayLayer) which made me lose the native subtitles support but let me tap into the play/pause/seek calls and enforce the needed rules. This way I was able to use the AVPictureInPictureController with a content source and delegate (the latter did the trick to tapping into the PiP calls). But with this, I lost the subtitles. The first thing that came to my mind was to implement support for the rendering of subtitles. Adding an AVPlayerItemLegibleOutput to the AVPlayerItem allowed me to get access to the subtitles, just to find out they were annotated with CoreMedia CMTextMark which don't seem to be automatically rendered by a CATextLayer. Thought of converting the NSAttributedString "styles" from Core Media to "normal" styles but then I would also need to add support for laying the subs correctly. Certainly, one way to do it but not sure it's easier. Couldn't find anything on the Core Media documentation that helped either. Then while digging around the AVPlayerItemOutput I saw the suppressesPlayerRendering and trying to use AVPlayerLayer and AVSampleBufferDisplayLayer together. The first one would render the subtitles while the other would do the video rendering. Made a sample and it sure works on the simulator, but when running on the device I get two layers of video playing and it seems that the suppressesPlayerRendering flag doesn't do anything. How can I tackle this problem?
Posted
by
Post not yet marked as solved
1 Replies
227 Views
The recent upgrade of the Mac OS seems to have removed some of the inspector bar tools from the NSTextView that formerly appears after setting usesInspectorBar to true. I see nothing in the documentation for any API for making these tools reappear. I notice that the TextEdit app's inspector bar is not missing them. Please tell me how to get my app's text view's inspector bar to look and behave like TextEdit.
Posted
by
Post not yet marked as solved
0 Replies
326 Views
My language learning app needs to support a lot of languages and text paragraphs containing 2 different languages are not uncommon. (e.g. German grammar explained in Arabic) Now, I want to integrate a custom font to make the design unique and consistent across multiple platforms (iOS, Android, Web), but there is basically no single Font that supports all languages. The question is: What is the recommended way of implementing that on the code level in SwiftUI? If I just hardcode: .font(Font.custom("myFont", size: 16)) then I guess it is not gonna work if the text contains a language not supported by my custom font. The Apple's default font seems to handle all languages perfectly, even if they are mixed together and I'd like to have something like that, but with a custom font. Specifically, I'd like to integrate FF Din font: https://www.myfonts.com/fonts/fontfont/ff-din/ with supported Languages: Western Europe, Vietnamese, Central/Eastern Europe, Baltic, Turkish, Romanian, Cyrillic, Greek So I am wondering what I would do about Chinese, Arabic, etc. Thanks
Posted
by
Post not yet marked as solved
1 Replies
378 Views
I'm trying to render text with Metal for my (2D) game. I'm using the system fonts, e.g. the SF Pro family for English texts. I render the glyphs onto an atlas texture, and then sample from this texture. My questions: I assume that, for copyright reasons, I'm not allowed to include a pre-rendered font atlas in my app. Is my assumption correct? I can, however, have the app generate the atlas when it's first opened, and then use it within the app, right? If 2. is true, then can the app save the atlas somewhere in the app's private storage, so that it would not need to re-generate the atlas the next time? Thanks!
Posted
by
Post not yet marked as solved
0 Replies
318 Views
We found that text rendering takes a lot of time as of iOS 15.2. We measured how much time it takes to assign values to text and attributedText of UILabel in iOS 14.5 simulator and iOS 15.2 simulator, respectively, using long enough and short enough text data. As a result, regardless of the text or attributedText, it was confirmed that iOS 15.2 takes about 4 times more time for a short enough text and 15 times more for a long enough text. And this is causing scrolling freezing. Anyone experiencing this issue? or how can I resolve it?
Posted
by
Post not yet marked as solved
0 Replies
132 Views
When I attempt to highlight text within an SVG on an iPhone, the blue selection bar is in the wrong position. Please see attached screenshots. You can see in my screenshots that the text magnifier is in the correct spot but not the blue selection bar. Has anyone run into this issue?
Posted
by