mason paisley
mason paisley

Reputation: 11

iOS ImageRenderer Unable to localize text correctly Bug

A simple view has misaligned localized content after being converted to an image using ImageRenderer. Regardless of the language, when using ImageRenderer, it will be converted to English incorrectly.

I tried to use UIGraphicsImageRenderer, but the UIGraphicsImageRenderer captures the image in an inaccurate position, and it will be offset resulting in a white border. And I don't know why in some cases it encounters circular references that result in blank images.

Code and simulator screenshots This is still problematic on real phone and TestFlight

I'm not sure what the problem is, I'm assuming it's an ImageRenderer bug.

    VStack(spacing: 8) {
    // The normal view
    let simpleView = VStack() {
        Text("连续生存")
        Text("总打卡天数")
        Text("\(0) days")
        Text("\(1) days")
        Text("\(2) days")
    }
    .padding(4)
    .background(Color.gray)
    
    simpleView // The normal view, language is Chinese
    
    simpleView // "\(1) days" is correctly converted to "1 day".
        .environment(\.locale, .init(identifier: "en"))
    
    // After converting to UIImage with ImageRenderer, the text becomes English, it should be Simplified Chinese.
    // and "\(1) days" is not converted to "1 day".
    let image: UIImage = ImageRenderer(content: simpleView).uiImage ?? UIImage(named: "error.image")!
        
    Image(uiImage: image)
}
.environment(\.locale, .init(identifier: "zh-Hans")) // Language set to Simplified Chinese

Localizable.strings:
    
"总打卡天数" = "Total Check-ins";
"连续生存" = "Streak";

Localizable.stringsdict:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>%lld days</key>
    <dict>
        <key>NSStringLocalizedFormatKey</key>
        <string>%#@Variable@</string>
        <key>Variable</key>
        <dict>
            <key>NSStringFormatSpecTypeKey</key>
            <string>NSStringPluralRuleType</string>
            <key>NSStringFormatValueTypeKey</key>
            <string>lld</string>
            <key>other</key>
            <string>%lld days</string>
            <key>one</key>
            <string>1 day</string>
            <key>zero</key>
            <string>0 day</string>
        </dict>
    </dict>
</dict>
</plist>

Upvotes: 1

Views: 101

Answers (1)

Daniel Amarante
Daniel Amarante

Reputation: 805

It seems that the view being used by the ImageRenderer is not applying the environment because both happen inside the same block of code, while the environment is applied outside.

The environment modifier being applied to the view transforms the view into a new view, but when you're passing it to ImageRenderer, this environment is not applied yet. If you apply it directly under the view like in the example with "en" it should work.

Upvotes: 0

Related Questions