iOS 13 introduced UIImage
instances that auto-adopt to the current UIUserInterfaceStyle
(aka light or dark mode). However, there seem to be only methods to construct such images from named or system images (imageNamed:inBundle:withConfiguration:
or systemImageNamed:withConfiguration:
).
Is there a way to dynamically generate a universal light/dark mode UIImage
from Core Graphics (e.g. using two CGImage
s or using UIGraphicsImageRenderer)?
I don't see any API for that but maybe I'm wrong.
SwiftUI lets us detect whether dark mode or light mode is currently enabled using the colorScheme environment key. If you declare this using @Environment , you can refer to it in your views and they will automatically be reloaded when the color scheme changes.
An object that manages image data in your app.
UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 20.0, 0.0, 0.0)]; UIImage *myimg = [UIImage imageNamed:@"A1. jpg"]; imageview. image=myimg; [imageview sizeToFit]; And don't forget to add image view to view hierarchy.
The isEqual(:) method is the only reliable way to determine whether two images contain the same image data. The image objects you create may be different from each other, even when you initialize them with the same cached image data.
+ (UIImage*)dynamicImageWithNormalImage:(UIImage*)normalImage darkImage:(UIImage*)darkImage{
if (normalImage == nil || darkImage == nil) {
return normalImage ? : darkImage;
}
if (@available(iOS 13.0, *)) {
UIImageAsset* imageAseset = [[UIImageAsset alloc]init];
// 注册 lightImage
UITraitCollection* lightImageTrateCollection = [UITraitCollection traitCollectionWithTraitsFromCollections:
@[[UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleLight],
[UITraitCollection traitCollectionWithDisplayScale:normalImage.scale]]];
[imageAseset registerImage:normalImage withTraitCollection:lightImageTrateCollection];
// 注册 darkImage
UITraitCollection* darkImageTrateCollection = [UITraitCollection traitCollectionWithTraitsFromCollections:
@[[UITraitCollection traitCollectionWithUserInterfaceStyle:UIUserInterfaceStyleDark],
[UITraitCollection traitCollectionWithDisplayScale:darkImage.scale]]];
[imageAseset registerImage:darkImage withTraitCollection:darkImageTrateCollection];
return [imageAseset imageWithTraitCollection:[UITraitCollection currentTraitCollection]];
}
else {
return normalImage;
}
}
maybe, that is what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With