Skip to content

Instantly share code, notes, and snippets.

@kyungpyoda
Last active June 3, 2021 06:50
Show Gist options
  • Save kyungpyoda/5b185cb321bbd14a0f17d4b1006eaa5a to your computer and use it in GitHub Desktop.
Save kyungpyoda/5b185cb321bbd14a0f17d4b1006eaa5a to your computer and use it in GitHub Desktop.
[Swift] iOS Change background color of UIImage
//
// 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