When do adjustsFontSizeToFitWidth or boundingRectWithSize change the context.actualScaleFactor?
Asked Answered
C

2

8

When does the actualScaleFactor of an NSStringDrawingContext change?

The documentation says:

"If you specified a custom value in the minimumScaleFactor property, when drawing is complete, this property contains the actual scale factor value that was used to draw the string."

My code:

myButton.titleLabel!.font = UIFont(name: "AmericanTypewriter-Bold", size: 40)
myButton.titleLabel?.adjustsFontSizeToFitWidth = true
myButton.setTitle("\(textString)", forState: .Normal)

let attributes = [NSFontAttributeName : myButton.titleLabel!.font]
let attributedString = NSMutableAttributedString(string:textString, attributes:attributes)

let context = NSStringDrawingContext()
context.minimumScaleFactor = myButton.titleLabel!.minimumScaleFactor

print("context: \(context.actualScaleFactor)")

let resultingRect = attributedString.boundingRectWithSize(myButton.titleLabel!.bounds.size, options: .UsesLineFragmentOrigin, context: context)

print("actual context after drawing: \(context.actualScaleFactor)")

//want to get the font size after adjustsFontSizeToFitWidth has done its magic:      
//let actualFontSize = myButton.titleLabel!.font.pointSize * context.actualScaleFactor

Console log for both text that fits without being shrunk and longer text that is adjusted to fit the label's width are both the same:

context: 0.0
actual context after drawing: 1.0

Any idea what step I am missing to get a real scaleFactor from context after the text has been sized to fit the label?

Chandlery answered 5/1, 2016 at 22:36 Comment(2)
Thank you for translating to swift. It works fine for me. I have a UILabel with actual font size 70pt, minimum scale factor 0.1, and "adjustsToFit" set to true. When executing your code AFTER viewDidAppear, my console output showed: "context: 0.0 actual context after drawing: 0.36 adjustedFontSize: 14.4". And indeed when I applied this adjustedFontSize to my label's font (after setting "adjustsToFit" to false), changing the text does not change the font size.Foreignborn
Most likely this answer will help you https://mcmap.net/q/941678/-setting-the-same-font-size-for-different-labels-after-scalingPredestination
B
0

do this in viewDidAppear... That worked for me

Brandtr answered 27/4, 2016 at 7:15 Comment(0)
M
0

The same problem as @RanLearns.

After add myButton.titleLabel!.minimumScaleFactor = 0.1 it worked for me

Mcclean answered 20/7, 2016 at 7:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.