apportable - Resource images are not accessible if

2019-09-06 15:21发布

问题:

When porting an iOS app to Android using apportable, resources within the app are not accessible (they fail to load at runtime) if they have been localized (different versions for different languages):

  1. Add a localized image to your project (different versions of the image for different languages) via Xcode - apportable will load these into the .apk package as assets under language specific folders. For example:

    assets/en.lproj/image.png        (generic english version)
    assets/zh-Hans.lproj/image.png   (simplified chinese version)
    assets/zh-Hant.lproj/image.png   (traditional chinese version)
    
  2. Attempt to load the image:

 UIImage *image = [UIImage imageNamed:imageName];   // This works under iOS but not under apportable

this returns nil if the image has been localised as described above.

回答1:

Below is a temporary workaround that works:

Utils.h:

#if defined(ANDROID) && defined(WORKAROUND_APPORTABLE_LOCALIZED_IMAGES)
#define LOCALIZEDIMAGE LocalizedUIImage
@interface LocalizedUIImage : UIImage
+(UIImage *)imageNamed:(NSString *)imageName;
@end
#else
#define LOCALIZEDIMAGE UIImage
#endif

Utils.m:

#if defined(ANDROID) && defined(WORKAROUND_APPORTABLE_LOCALIZED_IMAGES)
#import <Foundation/Foundation.h>
@implementation LocalizedUIImage
+(UIImage *)imageNamed:(NSString *)imageName {
    UIImage *image = nil;
    if ([imageName rangeOfString:@"/"].location == NSNotFound) {
        NSLocale *locale = [NSLocale currentLocale];
        NSString *localeId = [locale localeIdentifier];
        NSString *localizedImageName = [[localeId stringByAppendingString:@".lproj/"] stringByAppendingString:imageName];
        image = [UIImage imageNamed:localizedImageName];
        if (image == nil) { // Retry for a generic language version (ie:   en  rather than   en_US  )
            NSUInteger hyphenatedLocale = [localeId rangeOfString:@"_"].location;
            if (hyphenatedLocale != NSNotFound) {
                NSString *localizedImageName = [[[localeId substringToIndex:hyphenatedLocale] stringByAppendingString:@".lproj/"] stringByAppendingString:imageName];
                image = [UIImage imageNamed:localizedImageName];
            }
        }
    }
    if (image == nil)
        image = [UIImage imageNamed:imageName];
    return image;
}
@end
#endif

Use by:

UIImage *image = [LOCALIZEDIMAGE imageNamed:imageName];