apportable - Resource images are not accessible if they have been localized

社会主义新天地 提交于 2019-12-13 04:18:01

问题


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];


来源:https://stackoverflow.com/questions/24275658/apportable-resource-images-are-not-accessible-if-they-have-been-localized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!