Last active
June 3, 2021 06:50
-
-
Save kyungpyoda/5b185cb321bbd14a0f17d4b1006eaa5a to your computer and use it in GitHub Desktop.
[Swift] iOS Change background color of UIImage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UIImage+withBackground.swift | |
// | |
// Created by 홍경표 on 2021/04/12. | |
// | |
import UIKit | |
extension UIImage { | |
func withBackground(color: UIColor, opaque: Bool = true) -> UIImage { | |
UIGraphicsBeginImageContextWithOptions(size, opaque, scale) | |
guard let context = UIGraphicsGetCurrentContext(), | |
let image = cgImage else { return self } | |
let rect = CGRect(origin: .zero, size: size) | |
context.setFillColor(color.cgColor) | |
context.fill(rect) | |
context.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: size.height)) | |
context.draw(image, in: rect) | |
return UIGraphicsGetImageFromCurrentImageContext() ?? self | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment