Checking if UIGraphicsBeginImageContextWithOptions

2020-03-23 02:26发布

I'm working on an iOS app. It currently only works on iOS 4 since I use the following method on several occasions: "UIGraphicsBeginImageContextWithOptions". This method is only available in iOS 4 and therefor my app currently crashes/doesn't work on iPhone OS 3. Aside from this method there is no reason why the app should not work on iPhone OS 3. How do I make a check to see wether or not this method is available ? I've tried the following without succes:

if([self respondsToSelector:@selector(UIGraphicsBeginImageContextWithOptions)]) {
    UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0.0); // this will crop
}
else 
{
    UIGraphicsBeginImageContext(targetSize);

}

I've only tried variations like this:

if([self respondsToSelector:@selector(UIGraphicsBeginImageContextWithOptions:size:opaque:scale:)])

and

if([self respondsToSelector:@selector(UIGraphicsBeginImageContextWithOptions:)])

Without succes. Any help would be appreciated.

3条回答
Fickle 薄情
2楼-- · 2020-03-23 02:40

UIGraphicsBeginImageContextWithOptions is a C function, so you can't use Objective-C methods like -respondsToSelector: to test its existence.

You could, however, weak link the UIKit framework, and then check if UIGraphicsBeginImageContextWithOptions is NULL:

if (UIGraphicsBeginImageContextWithOptions != NULL) {
   UIGraphicsBeginImageContextWithOptions(...);
} else {
   UIGraphicsBeginImageContext(...);
}
查看更多
叛逆
3楼-- · 2020-03-23 02:45

I know this is an old question, but with new Xcode and iOS versions (upper than 9) any of this methods work for me.

I always check the system version in this way:

NSString *sysver = [[UIDevice currentDevice] systemVersion];
NSArray *versionNums = [sysver componentsSeparatedByString:@"."];
int majorVersion = [versionNums[0] intValue];
if (majorVersion > 3){
    UIGraphicsBeginImageContextWithOptions(...);
}
else{
    UIGraphicsBeginImageContext(...);
}

I hope this could help anyone.

查看更多
Anthone
4楼-- · 2020-03-23 02:57

I have the same problem. You could try testing the system version. This seems to work for me on the devices I tested.

char majorVersion = [[[UIDevice currentDevice] systemVersion] characterAtIndex: 0];
if (majorVersion == '2' || majorVersion == '3')
     UIGraphicsBeginImageContext(...);
else
     UIGraphicsBeginImageContextWithOptions(...);
查看更多
登录 后发表回答