How to Create a UIImage With a Solid Color in Swift

How to Create a UIImage With a Solid Color in Swift

Written by

in

Quick answer: UIImage has no initializer that takes a color, so you draw one: fill a bitmap context with the UIColor and wrap the result. The modern way is UIGraphicsImageRenderer, usually wrapped in a small UIColor extension that returns a 1×1 image you can stretch or resize.

Why this happens

UIImage is a container for bitmap data (or a CGImage, or a symbol/asset). It has no notion of “fill color” — there is no UIImage(color:) in UIKit. A color only becomes pixels when something draws it into a graphics context, so creating a solid image means allocating a bitmap of the size you want, filling it, and reading the bitmap back out.

The old recipe used UIGraphicsBeginImageContextWithOptions plus UIRectFill. That still works, but it is a global, stateful API: you must remember to call UIGraphicsEndImageContext() on every path, and the scale handling is easy to get wrong. Apple’s replacement, UIGraphicsImageRenderer (iOS 10 and later), owns its context, takes a format object for scale and opacity, and returns the finished UIImage from a closure — no cleanup required.

How to fix it

1. Add a UIColor extension backed by UIGraphicsImageRenderer

This is the version to use in new code. It defaults to a 1×1 point image, which is all you need when the image will be stretched anyway.

import UIKit

extension UIColor {
    func image(size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
        let format = UIGraphicsImageRendererFormat.default()
        format.scale = 1
        format.opaque = cgColor.alpha >= 1.0

        return UIGraphicsImageRenderer(size: size, format: format).image { context in
            self.setFill()
            context.fill(CGRect(origin: .zero, size: size))
        }
    }
}

Usage:

let orange = UIColor.orange.image(size: CGSize(width: 128, height: 128))
let oneByOne = UIColor.systemBlue.image()

setFill() sets the current fill color on the context the renderer prepared, and context.fill(_:) paints the whole rectangle with it. You can also skip setFill() and write context.cgContext.setFillColor(cgColor) if you prefer working with Core Graphics directly.

2. Get scale and opacity right

Two format properties cause most of the confusion:

  • scale — UIGraphicsImageRendererFormat.default() inherits the main screen’s scale, so a 1×1 point image becomes 2×2 or 3×3 pixels on a Retina device. For a flat fill that is wasted memory, so setting scale = 1 is usually what you want. Set it back to the screen scale only if the image contains detail that must stay crisp.
  • opaque — when the color is fully opaque, opaque = true drops the alpha channel and produces a smaller, faster image. If the color has any transparency, leave it false, otherwise the renderer composites your color against black and the alpha is lost.

If you want the caller to decide, expose the format instead of hard-coding it:

extension UIColor {
    func image(size: CGSize, format: UIGraphicsImageRendererFormat) -> UIImage {
        UIGraphicsImageRenderer(size: size, format: format).image { context in
            self.setFill()
            context.fill(CGRect(origin: .zero, size: size))
        }
    }
}

3. Use a UIImage convenience initializer instead

If you prefer the call site to read UIImage(color:), an extension can add a convenience initializer. Convenience initializers are allowed in class extensions, so this compiles cleanly:

import UIKit

extension UIImage {
    convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
        let rendered = UIGraphicsImageRenderer(size: size).image { context in
            color.setFill()
            context.fill(CGRect(origin: .zero, size: size))
        }
        guard let cgImage = rendered.cgImage else { return nil }
        self.init(cgImage: cgImage)
    }
}
let red = UIImage(color: .red)
let red200 = UIImage(color: .red, size: CGSize(width: 200, height: 200))

The initializer is failable only because cgImage is optional in the type system; a renderer-produced image always has one. If you dislike the ? at every call site, drop the guard and force-unwrap-free by making the initializer non-failable and calling self.init(cgImage:) on the unwrapped value — but keeping it failable is the safer habit.

4. Stretch a 1×1 image without artifacts

A 1×1 point image in a UIImageView with the default .scaleToFill content mode fills the frame, which is fine. If you use it as a backgroundImage on a button, a navigation bar, or a table cell, wrap it as a resizable image so UIKit tiles or stretches it correctly:

let fill = UIColor.systemBlue.image()
    .resizableImage(withCapInsets: .zero, resizingMode: .stretch)

let button = UIButton(type: .system)
button.setBackgroundImage(fill, for: .normal)

Use .tile instead of .stretch if you ever generate a small pattern rather than a flat color.

5. In SwiftUI, skip the UIImage

If the goal is a colored rectangle on screen, SwiftUI already has it — no bitmap needed:

Rectangle()
    .fill(Color.orange)
    .frame(width: 128, height: 128)

You only need a UIImage when an API demands one (a UIButton background, a CGImage for Core Graphics work, a share sheet item). In that case, on iOS 16 and later, ImageRenderer converts a SwiftUI view into a UIImage:

import SwiftUI

@MainActor
func solidImage(_ color: Color, size: CGSize) -> UIImage? {
    let renderer = ImageRenderer(
        content: Rectangle()
            .fill(color)
            .frame(width: size.width, height: size.height)
    )
    renderer.scale = 1
    return renderer.uiImage
}

Going the other direction is simpler: Color(uiColor:) turns any UIColor into a SwiftUI color.

How to prevent it

  • Prefer UIGraphicsImageRenderer over UIGraphicsBeginImageContextWithOptions; the renderer cannot leak a context you forgot to end.
  • Set format.scale = 1 for flat fills and keep the screen scale only for detailed artwork.
  • Set format.opaque = true only when the color’s alpha is 1.0.
  • Build the image once and store it — regenerating it inside cellForRowAt or a body getter burns CPU for identical pixels.
  • If you only need a background color, use view.backgroundColor or CALayer.backgroundColor instead of an image at all.

FAQ

Why is my solid color image only one pixel?

Because the default size is CGSize(width: 1, height: 1). A 1×1 image is intentional for stretching, but if you place it in a UIImageView with .center content mode you will see a single dot. Pass an explicit size, or set the content mode to .scaleToFill.

Does this work with colors that have transparency?

Yes. UIColor(white: 0, alpha: 0.5) renders correctly as long as format.opaque stays false. Setting opaque = true on a translucent color produces a darker, fully opaque result because the renderer has no alpha channel to store the transparency in.

Can I create the image off the main thread?

UIGraphicsImageRenderer creates and owns its own bitmap context, so it does not depend on the view hierarchy or the main run loop, and it is commonly used from background queues when generating thumbnails or placeholders. Anything that touches UIKit views — including ImageRenderer in SwiftUI — should stay on the main actor.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.