Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Blend Two Images Together in SwiftUI
Written by Team Kodeco

Blending two images together in SwiftUI is a great way to create an intriguing composition.

To blend two images, you use the blendMode modifier provided by SwiftUI. This modifier takes a BlendMode enumeration value as its parameter, indicating how the images should be combined.

Here’s an example that blends a photo of a tent at sunrise with a wavy pattern overlay:

struct ContentView: View {
  var body: some View {
    ZStack {
      Image("SunriseTent")
        .resizable()
        .scaledToFill()
        .edgesIgnoringSafeArea(.all)

      Image("WavyPattern")
        .resizable()
        .scaledToFill()
        .blendMode(.multiply)
        .opacity(0.7)
    }
  }
}

Note: If you want to try out the examples, you can download an archive of all the images used in this section here.

The preview should look as follows:

Use blendMode to combine images in SwiftUI.
Use blendMode to combine images in SwiftUI.

In this example, SunriseTent is the base image and WavyPattern is the overlay image. The blend mode is set to .multiply, and the overlay image’s opacity is set to 0.7 to ensure that the base image is still visible.

The choice of blend mode (multiply, screen, overlay, darken, lighten and so on) will depend on the specific effect you want to achieve. Experiment with different blend modes and opacity values to see what works best for your specific images.

It’s worth mentioning that the size of the overlay image does not need to match the size of the underlying image. You can also apply other modifiers to the blended image, such as transparency or rotation, to achieve unique visual effects.

In conclusion, blending two images together in SwiftUI is a powerful way to add dynamic visual effects to your app. By using the blendMode modifier, you can easily blend and compose images in a variety of ways. Give it a try and experiment with different blend modes and image combinations to create something truly unique!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.