EEYatHo 앱 깎는 이야기

Swift ) Dynamic Image - EEYatHo iOS 본문

iOS, Swift/Swift Theory

Swift ) Dynamic Image - EEYatHo iOS

EEYatHo 2022. 10. 15. 14:57
반응형

 

Dynamic Image


런타임에서 다크모드, 라이트모드 변경에 대응하는 다이나믹 이미지 ( Dynamic Image ) 가 있다. ( Dynamic Color 처럼 )

 

다이나믹 이미지는 AssetCatalog 나 Code 로 생성할 수 있다.

 

 

 

1. AssetCatalog 로 Dynamic Image 생성하기


UIImage(named: "MyImageName")

 

 

 

2. Code 로 Dynamic Color 생성하기


UIImage 에게 추가 작업 ( resize 등 ) 을 하게되면, 코드로 생성하는게 필요해진다.

 

func dynamicImage(lightImage: UIImage, darkImage: UIImage) -> UIImage {
    
    let darkTC = UITraitCollection(traitsFrom: [.current, .init(userInterfaceStyle: .dark)])
    lightImage.imageAsset?.register(darkImage, with: darkTC)
    
    return lightImage
}

 

 

 

3. Dynamic Image 를 Light Image, Dark Image 로 분해하기


let lightTC = UITraitCollection(traitsFrom: [.current, .init(userInterfaceStyle: .light)])
let darkTC = UITraitCollection(traitsFrom: [.current, .init(userInterfaceStyle: .dark)])

let myImage = UIImage(named: "MyImageName")

let lightImage = myImage.imageAsset?.image(with: lightTC)
let darkImage = myImage.imageAsset?.image(with: darkTC)

 

 

 

 

* Dynamic Image 를 trait 를 잃지 않게 resize 하기


extension UIImage {

    static func resizeWithDynamic(size: CGSize, image: UIImage) -> UIImage {
        
        let lightTC = UITraitCollection(traitsFrom: [.current, .init(userInterfaceStyle: .light)])
        let darkTC = UITraitCollection(traitsFrom: [.current, .init(userInterfaceStyle: .dark)])
        
        let lightImage = image.imageAsset?.image(with: lightTC) ?? image
        let darkImage = image.imageAsset?.image(with: darkTC) ?? image
        
        let resizedLightImage = lightImage.resizeImage(targetSize: size)
        let resizedDarkImage = darkImage.resizeImage(targetSize: size)
        
        resizedLightImage.imageAsset?.register(resizedDarkImage, with: darkTC)
        
        return resizedLightImage
    }
    
    private func resizeImage(targetSize: CGSize) -> UIImage {
        
        let size = self.size
        
        let widthRatio  = targetSize.width  / size.width
        let heightRatio = targetSize.height / size.height
        
        var newSize: CGSize
        if widthRatio < heightRatio {
            newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
        } else {
            newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio)
        }
        
        let rect = CGRect(origin: .zero, size: newSize)
        
        UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage ?? self
    }
}
Comments