How to get the device's scale factor?

Objective CIosUiimage

Objective C Problem Overview


I've been using UIGraphicsBeginImageContextWithOptions() and I noticed that the last field in that method is a scalefactor. And the apple docs says, if I want to set it to 0.0, then it will use the default scale factor of the device's main screen. Is there a way to get that default scale factor via property or method?

Objective C Solutions


Solution 1 - Objective C

The device's scale factor is a property of UIScreen. You can obtain it by:

[UIScreen mainScreen].scale;

Documentation here.

Solution 2 - Objective C

Swift 3+ version:

UIScreen.main.scale

Solution 3 - Objective C

Swift5+ / macOS Big Sur:

let backingScaleFactor = NSScreen.main?.backingScaleFactor

Solution 4 - Objective C

Swift 5+

let scale = UIScreen.main.scale
print("scale is:\(scale)")

Solution 5 - Objective C

Hope it will help you

 CGSize textcontent =CGSizeMake(width, height);
UIGraphicsBeginImageContext(textcontent);
if ([UIScreen instancesRespondToSelector:@selector(scale)] && [[UIScreen mainScreen] scale] == 2.0f)
{
    UIGraphicsBeginImageContextWithOptions(textcontent, YES, 1.0f);
}
else
{
    UIGraphicsBeginImageContext(textcontent);
}
 [view.layer renderInContext:UIGraphicsGetCurrentContext()];
 viewImage = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();
 return viewImage;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionManOxView Question on Stackoverflow
Solution 1 - Objective CjrturtonView Answer on Stackoverflow
Solution 2 - Objective CPaulo VenturiView Answer on Stackoverflow
Solution 3 - Objective CMichel StormsView Answer on Stackoverflow
Solution 4 - Objective CLakhdeep SinghView Answer on Stackoverflow
Solution 5 - Objective CSudha TiwariView Answer on Stackoverflow