Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create images dynamically for a trait collection
@interface UIImage (DynamicProvider)
+ (UIImage *)imageWithDynamicProvider:(UIImage * (^)(UITraitCollection *traitCollection))dynamicProvider API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);
- (UIImage *)initWithDynamicProvider:(UIImage * (^)(UITraitCollection *traitCollection))dynamicProvider API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);
@end
@implementation UIImage (DynamicProvider)
+ (UIImage *)imageWithDynamicProvider:(UIImage * (^)(UITraitCollection *traitCollection))dynamicProvider API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos)
{
return [[UIImage alloc] initWithDynamicProvider:dynamicProvider];
}
- (UIImage *)initWithDynamicProvider:(UIImage * (^)(UITraitCollection *traitCollection))dynamicProvider API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos)
{
UITraitCollection *currentTraitCollection = UITraitCollection.currentTraitCollection;
UIImage *image = dynamicProvider(currentTraitCollection);
// User Interface Styles (Light and Dark Modes)
NSArray<UITraitCollection *> *userInterfaceStyleTraitCollections = @[
[UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleLight],
[UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleDark],
];
// Accessibility Contrasts (Regular and High Contrast Modes)
NSArray<UITraitCollection *> *accessibilityContrastTraitCollections = @[
[UITraitCollection traitCollectionWithAccessibilityContrast:UIAccessibilityContrastNormal],
[UITraitCollection traitCollectionWithAccessibilityContrast:UIAccessibilityContrastHigh],
];
// Enumerate all combinations. I wish there were a way to do this lazily (like with `-[NSImage imageWithSize:flipped:drawingHandler:]`).
for (UITraitCollection *userInterfaceStyleTraitCollection in userInterfaceStyleTraitCollections) {
for (UITraitCollection *accessibilityContrastTraitCollection in accessibilityContrastTraitCollections) {
UITraitCollection *combinedTraitCollection = [UITraitCollection traitCollectionWithTraitsFromCollections:@[
currentTraitCollection,
userInterfaceStyleTraitCollection,
accessibilityContrastTraitCollection,
]];
UIImage *imageCompatibleWithTraitCollection = dynamicProvider(combinedTraitCollection);
[image.imageAsset registerImage:imageCompatibleWithTraitCollection withTraitCollection:combinedTraitCollection];
}
}
return image;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.