SwiftUI series 11: Creating a Thumbnail Maker App in SwiftUI: Basic Text Floating Above Image App
In this tutorial, we'll build a simple but powerful Thumbnail Maker app using SwiftUI. This app allows users to select an image from their photo library and add custom text overlays to create engaging thumbnails.
Prerequisites
- Xcode 15 or later
- Basic knowledge of SwiftUI
- iOS 17 or later
Step-by-Step Guide
1. Setting Up the Project
First, create a new SwiftUI project in Xcode and name it "ThumbnailMaker". The main functionality will be in ContentView.swift
.
2. Import Required Frameworks
import SwiftUI
import PhotosUI
3. Creating the State Variables
@State private var selectedImage: UIImage?
@State private var imageSelection: PhotosPickerItem?
@State private var overlayText: String = ""
These state variables will:
- Store the selected image
- Handle the PhotosPicker selection
- Manage the overlay text input
4. Building the User Interface
var body: some View {
VStack(spacing: 20) {
// Image picker button
PhotosPicker(selection: $imageSelection,
matching: .images) {
Text("Select Image")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
}
// Image display with text overlay
if let selectedImage {
ZStack {
Image(uiImage: selectedImage)
.resizable()
.scaledToFit()
.frame(maxHeight: 300)
Text(overlayText)
.font(.system(size: 32, weight: .bold))
.foregroundColor(.white)
.shadow(color: .black, radius: 3, x: 1, y: 1)
.multilineTextAlignment(.center)
.padding()
}
}
// Text input field
TextField("Enter overlay text", text: $overlayText)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding(.horizontal)
}
.padding()
}
5. Handling Image Selection
.onChange(of: imageSelection) { oldValue, newValue in
Task {
if let data = try? await newValue?.loadTransferable(type: Data.self),
let uiImage = UIImage(data: data) {
selectedImage = uiImage
}
}
}
Key Features Explained
-
Photo Selection: Using
PhotosPicker
, we provide a simple way to select images from the device's photo library. -
Image Display: The selected image is displayed using SwiftUI's
Image
view, configured to maintain aspect ratio and fit within a reasonable size. -
Text Overlay: Users can add custom text that appears centered over the image with a professional-looking shadow effect.
-
Responsive Layout: The app uses
VStack
for vertical organization andZStack
for overlaying text on the image.
Customization Options
You can enhance this basic version by:
- Adding different text styles and colors
- Implementing text position controls
- Adding export functionality
- Including filters or image adjustments