Picture Headline
A headline with living pictures stuck between its words like a collage, each opening into a tilted sticker as the words rise.
Live preview
// Copyright (c) 2026 Saivion Hayes
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, and distribute the Software as part of
// an application, website, or product, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// Commons Clause Restriction
//
// You may use this Software, including for any commercial purpose, so long as
// you do not sell, sublicense, or redistribute the components themselves, whether
// alone, in a bundle, or as a ported version.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import SwiftUI
/// A headline with pictures stuck between its words like stickers, revealed in reading order.
///
/// Write it as a list of segments: strings are words, pictures sit where you put them.
///
/// ```swift
/// PictureHeadline(["Slow", .art(.sun), "mornings, long", .art(.waves), "walks and early", .art(.moon), "nights."])
/// .font(.system(size: 40, weight: .semibold))
/// ```
///
/// Words are set in the house weight, semibold. Pictures are sized from the font, so they follow Dynamic Type and every
/// font you set. Each lands as a sticker: a white rim, a soft shadow and a small tilt that alternates along the
/// headline, with crop marks flashing at its corners. Press and hold one to lift it. Text wraps word by word and a
/// picture never breaks from the row it lands on.
///
/// - Parameters:
/// - segments: Words (string literals) and pictures (`.art`, `.image`, `.symbol`), in reading order.
/// - alignment: Row alignment, like `multilineTextAlignment`.
/// - duration: Target time for the whole reveal, in seconds. The stagger is sized from the number of words and pictures, so short and long headlines both land in about this long.
/// - delay: Delay before the first word starts.
/// - revealOnScroll: When true, the reveal waits until the headline scrolls into view (iOS 18). Below iOS 18 it reveals on appear.
/// - trigger: Change this value to replay the reveal.
/// - haptics: A light tick as each picture lands and when one is lifted. On by default.
/// - style: Picture size, corner rounding, tilt, rim, crop marks, lifting, drift and the opening spring.
public struct PictureHeadline: View {
/// A word run or a picture. String literals become words, so a headline reads as a plain list.
public enum Segment: ExpressibleByStringLiteral {
/// One or more words. Split on whitespace; each word rises on its own.
case text(String)
/// A picture between the words. `width` is in picture heights (2.4 is a wide frame, 1 a square), `label` is read by VoiceOver.
case picture(Picture, width: CGFloat = 2.4, label: String? = nil)
public init(stringLiteral value: String) { self = .text(value) }
/// A built-in house-palette scene that keeps drifting after it opens.
public static func art(_ scene: Scene, width: CGFloat = 2.4, label: String? = nil) -> Segment {
.picture(.art(scene), width: width, label: label)
}
/// Your own image, filled into the frame. It drifts slowly unless `Style.drift` is off.
public static func image(_ image: Image, width: CGFloat = 2.4, label: String? = nil) -> Segment {
.picture(.image(image), width: width, label: label)
}
/// An SF Symbol on a solid block, square by default.
public static func symbol(_ systemName: String, fill: Color, ink: Color = Color(red: 0.078, green: 0.078, blue: 0.078), width: CGFloat = 1.3, label: String? = nil) -> Segment {
.picture(.symbol(systemName, fill: fill, ink: ink), width: width, label: label)
}
}
/// What fills a picture's frame.
public enum Picture {
case art(Scene)
case image(Image)
case symbol(String, fill: Color, ink: Color)
}
/// Built-in scenes, drawn in the house palette so a headline looks finished before you have artwork.
public enum Scene: CaseIterable, Sendable {
/// Our red mascot as a sun, settling into sand.
case sun
/// Bands of sea sliding past each other.
case waves
/// A crescent with twinkling stars on a night sky.
case moon
/// Layered green hills in slow parallax.
case hills
/// A white bloom turning on lilac.
case bloom
}
/// Visual tuning. `standard` matches the SwiftPieces house look.
public struct Style: Sendable {
/// Picture height as a fraction of the line height.
public var pictureHeight: CGFloat
/// Corner radius as a fraction of the picture height. 0.5 makes a capsule.
public var cornerRadius: CGFloat
/// Whether pictures keep moving after they open: scenes drift and images pan slowly. Off under Reduce Motion.
public var drift: Bool
/// Duration of the dot-to-frame spring, in seconds.
public var openDuration: Double
/// Bounce of the opening spring: how far a sticker swells past its full width before it settles.
public var openBounce: Double
/// The largest resting tilt, in degrees. Pictures alternate around it like stickers placed by hand; 0 lays them flat.
public var tilt: Double
/// Width of the sticker rim as a fraction of the picture height. 0 drops the rim.
public var rim: CGFloat
/// Colour of the sticker rim.
public var rimColor: Color
/// Whether crop marks flash at a picture's corners as it lands.
public var cropMarks: Bool
/// Whether pressing and holding a picture lifts it, straight and forward, until you let go.
public var lifts: Bool
public init(
pictureHeight: CGFloat = 0.82,
cornerRadius: CGFloat = 0.26,
drift: Bool = true,
openDuration: Double = 0.7,
openBounce: Double = 0.28,
tilt: Double = 4,
rim: CGFloat = 0.07,
rimColor: Color = .white,
cropMarks: Bool = true,
lifts: Bool = true
) {
self.pictureHeight = pictureHeight
self.cornerRadius = cornerRadius
self.drift = drift
self.openDuration = openDuration
self.openBounce = openBounce
self.tilt = tilt
self.rim = rim
self.rimColor = rimColor
self.cropMarks = cropMarks
self.lifts = lifts
}
public static let standard = Style()
}
@Environment(\.accessibilityReduceMotion) private var reduceMotion
/// The trigger the headline is showing, shared with every copy of the reveal.
@State private var showing: Showing
private let segments: [Segment]
private let alignment: TextAlignment
private let duration: Double
private let delay: Double
private let revealOnScroll: Bool
private let trigger: AnyHashable
private let haptics: Bool
private let style: Style
public init(
_ segments: [Segment],
alignment: TextAlignment = .leading,
duration: Double = 1.2,
delay: Double = 0,
revealOnScroll: Bool = false,
trigger: AnyHashable = 0,
haptics: Bool = true,
style: Style = .standard
) {
self.segments = segments
self.alignment = alignment
self.duration = duration
self.delay = delay
self.revealOnScroll = revealOnScroll
self.trigger = trigger
self.haptics = haptics
self.style = style
_showing = State(initialValue: Showing(trigger))
}
public var body: some View {
// Each trigger value is its own copy of the reveal, so a replay swaps copies in the same update that brings
// any new segments: the outgoing copy keeps the words it was showing while it fades.
let run = Run(trigger: trigger, showing: showing)
// True only in the update that starts a replay, before `onChange` records the new trigger. The new copy then
// rises a beat behind the old one's fade, so the old words are nearly gone before the new ones surface.
let replay = showing.trigger != trigger
// A ZStack, so a replay's outgoing and incoming headlines share one place instead of stacking. The outgoing
// copy no longer takes part in layout, so the headline is sized by the incoming one from the first frame.
ZStack {
Reveal(items: items, alignment: alignment, duration: duration, delay: delay + (replay ? 0.15 : 0), revealOnScroll: revealOnScroll, haptics: haptics, style: style, run: run)
.id(trigger)
.transition(Outgoing())
}
.animation(PieceMotion(reduceMotion: reduceMotion).dismiss, value: trigger)
.fontWeight(.semibold)
.accessibilityElement(children: .ignore)
.accessibilityLabel(spoken)
.accessibilityAddTraits(.isHeader)
.onChange(of: trigger) { _, now in showing.trigger = now }
}
/// A replay's outgoing headline fades out and stops taking touches, so a press lands on the new one.
private struct Outgoing: Transition {
func body(content: Content, phase: TransitionPhase) -> some View {
let leaving = phase == .didDisappear
content
.opacity(leaving ? 0 : 1)
.allowsHitTesting(!leaving)
}
}
/// The trigger the headline is showing now. A reference, because a replay's outgoing copy stops receiving inputs
/// once it is removed, yet still has to see that it was replaced.
@MainActor private final class Showing {
var trigger: AnyHashable
init(_ trigger: AnyHashable) { self.trigger = trigger }
}
/// One copy of the reveal: the trigger it runs for. Before a landing tick, crop marks, drift or a lift tick it
/// checks `retired`, so a replay's outgoing copy goes quiet as it fades.
private struct Run {
let trigger: AnyHashable
let showing: Showing
@MainActor var retired: Bool { showing.trigger != trigger }
}
/// How long after its start a picture lands: when its frame first reaches about its full width on the opening
/// spring (0.35 s for the standard style), or as the fade ends under Reduce Motion. The tick, the crop marks and
/// the drift all start on this beat.
private static func landing(_ style: Style, reduceMotion: Bool) -> Double {
// `PieceMotion.reveal` under Reduce Motion is a 0.2 s fade.
guard !reduceMotion else { return 0.2 }
let spring = Spring(duration: max(0.05, style.openDuration), bounce: style.openBounce)
var t = 0.0
while t < 3, spring.value(target: 1.0, time: t) < 0.97 { t += 1.0 / 120 }
return t
}
/// The headline as one string for VoiceOver: the words, plus any picture labels where they sit.
private var spoken: String {
segments.compactMap { segment -> String? in
switch segment {
case .text(let words): words
case .picture(_, _, let label): label
}
}
.joined(separator: " ")
}
/// Every word and picture, in reading order, each with its place in the stagger.
private var items: [Item] {
var items: [Item] = []
for segment in segments {
switch segment {
case .text(let words):
for word in words.split(whereSeparator: \.isWhitespace) {
items.append(Item(id: items.count, kind: .word(String(word))))
}
case .picture(let picture, let width, _):
items.append(Item(id: items.count, kind: .picture(picture, width: max(0.5, width))))
}
}
return items
}
fileprivate struct Item: Identifiable {
enum Kind {
case word(String)
case picture(Picture, width: CGFloat)
}
let id: Int
let kind: Kind
var isPicture: Bool { if case .picture = kind { true } else { false } }
}
/// Recreated (via `.id(trigger)`) on every replay so its `revealed` state starts fresh.
private struct Reveal: View {
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var revealed = false
@State private var ticks = 0
let items: [Item]
let alignment: TextAlignment
let duration: Double
let delay: Double
let revealOnScroll: Bool
let haptics: Bool
let style: Style
let run: Run
/// Each item takes ~0.6 s to land; the rest of `duration` is spread across the stagger.
private var stagger: Double {
guard items.count > 1, !reduceMotion else { return 0 }
return max(0, duration - 0.6) / Double(items.count - 1)
}
private func start(_ item: Item) -> Double { delay + Double(item.id) * stagger }
/// Each picture's resting tilt: alternating sides and sizes, so a row reads as placed by hand.
private func tilt(_ item: Item) -> Double {
let pattern: [Double] = [-1, 0.75, -0.55, 1, -0.8, 0.6]
let ordinal = items.prefix(item.id).filter(\.isPicture).count
return style.tilt * pattern[ordinal % pattern.count]
}
var body: some View {
Group {
if #available(iOS 18, *), revealOnScroll {
flow.onScrollVisibilityChange(threshold: 0.35) { visible in
if visible { revealed = true }
}
} else {
flow.onAppear { revealed = true }
}
}
.sensoryFeedback(.impact(weight: SensoryFeedback.Weight.light, intensity: 0.7), trigger: ticks)
.task(id: revealed) {
guard revealed, haptics else { return }
let landing = PictureHeadline.landing(style, reduceMotion: reduceMotion)
if reduceMotion {
// Everything fades in together, so one tick marks the landing.
guard items.contains(where: \.isPicture) else { return }
try? await Task.sleep(for: .seconds(delay + landing))
if !Task.isCancelled, !run.retired { ticks += 1 }
return
}
// One tick per picture as its frame lands, on the beat of its crop marks.
var elapsed = 0.0
for item in items where item.isPicture {
let at = start(item) + landing
try? await Task.sleep(for: .seconds(max(0, at - elapsed)))
if Task.isCancelled || run.retired { return }
elapsed = at
ticks += 1
}
}
}
private var flow: some View {
HeadlineFlow(alignment: alignment) {
ForEach(items) { item in
switch item.kind {
case .word(let word):
WordView(word: word, revealed: revealed, reduceMotion: reduceMotion, delay: start(item))
case .picture(let picture, let width):
PictureSticker(picture: picture, width: width, open: revealed, reduceMotion: reduceMotion, delay: start(item), tilt: tilt(item), haptics: haptics, style: style, run: run)
}
}
}
}
}
/// A word that rises from behind its own baseline.
private struct WordView: View {
let word: String
let revealed: Bool
let reduceMotion: Bool
let delay: Double
var body: some View {
let hidden = !revealed
let rises = !reduceMotion
// Words are read: they rise at the calm reveal's pace without its give, so a word never bobs past its
// baseline. A literal on purpose, tied to calm's duration: `value` has no give but is quicker. A fade
// under Reduce Motion.
let rise: Animation = rises ? .spring(duration: PieceMotion.calm.duration, bounce: 0) : PieceMotion(reduceMotion: reduceMotion).reveal
Text(word)
.opacity(hidden && !rises ? 0 : 1)
.visualEffect { content, proxy in
content.offset(y: hidden && rises ? proxy.size.height * 1.05 : 0)
}
.animation(rise.delay(delay), value: revealed)
// Clips the rise at the word's own bottom edge and leaves the top open, so accents are never cut.
.mask(Rectangle().padding(.horizontal, -40).padding(.top, -400))
}
}
/// One picture in its slot, lifted above its neighbours while it is pressed.
private struct PictureSticker: View {
let picture: Picture
let width: CGFloat
let open: Bool
let reduceMotion: Bool
let delay: Double
let tilt: Double
let haptics: Bool
let style: Style
let run: Run
@State private var pressed = false
/// Holds that lasted long enough to count as a lift, one tick each.
@State private var holds = 0
var body: some View {
PictureSlot(width: width, height: style.pictureHeight) {
Text(verbatim: "Hg").hidden()
PictureFrame(picture: picture, open: open, pressed: pressed, reduceMotion: reduceMotion, delay: delay, tilt: tilt, style: style, run: run)
}
.zIndex(pressed ? 1 : 0)
// Pressing is reported from touch-down until the finger lifts, so the sticker peels up at once and stays up
// while held. Once the hold passes, the press completes and claims the touch, so a Button or tap gesture
// around the headline doesn't also fire. Moving past the tolerance first ends it, so scrolling over the
// headline still scrolls. Every report writes `pressed`, so it always resets.
.onLongPressGesture(minimumDuration: 0.12, maximumDistance: 14, perform: {
// The tick lands as the hold passes, so a quick tap or a scroll that starts on a sticker stays silent.
if haptics, style.lifts, open, !run.retired { holds += 1 }
}, onPressingChanged: { down in
pressed = down && style.lifts && open
})
.sensoryFeedback(.impact(weight: SensoryFeedback.Weight.light, intensity: 0.8), trigger: holds)
}
}
/// A picture as a sticker: a dot that opens into a rounded frame with a white rim and a soft shadow,
/// landing at its tilt on a spring, its contents settling from a slight zoom, with crop marks snapping in
/// at its corners. Pressed, it straightens and lifts forward.
private struct PictureFrame: View {
let picture: Picture
let open: Bool
let pressed: Bool
let reduceMotion: Bool
let delay: Double
let tilt: Double
let style: Style
let run: Run
@Environment(\.colorScheme) private var colorScheme
@State private var marksShown = false
/// When the picture landed. Its drift starts here, from the rest pose; until then it holds still.
@State private var landedAt: Date?
var body: some View {
let motion = PieceMotion(reduceMotion: reduceMotion)
// The frame leads on the piece's own spring (`openDuration`, `openBounce`). The dot is there at once, the
// tilt lands a beat behind the frame and a touch looser, and the picture settles from its zoom just after the
// frame lands, with no overshoot so its edges never pull in from the rim. Under Reduce Motion only the fade runs.
let opening = Spring(duration: style.openDuration, bounce: style.openBounce)
let frameIn = (reduceMotion ? motion.reveal : .spring(opening)).delay(delay)
let fadeIn = (reduceMotion ? motion.reveal : .spring(PieceMotion.tight)).delay(delay)
let tiltIn = motion.follow(opening, rank: 1).delay(delay + 0.06)
let settleIn = motion.follow(Spring(duration: style.openDuration, bounce: 0), rank: 2).delay(delay)
GeometryReader { proxy in
let size = proxy.size
let radius = size.height * min(0.5, max(0, style.cornerRadius))
let shown = open || reduceMotion
let rim = size.height * max(0, style.rim)
let lift = pressed && !reduceMotion
content(size)
.frame(width: size.width, height: size.height)
.scaleEffect(shown ? 1 : 1.3)
.animation(settleIn, value: open)
// Under Reduce Motion a held sticker shifts its brightness instead of lifting: darker in light mode,
// lighter in dark mode, so it stands off a dark page rather than sinking into it.
.brightness(pressed && reduceMotion ? (colorScheme == .dark ? 0.1 : -0.08) : 0)
// The opening: a dot as tall as the frame widens to the full frame. The drawn frame and its rim widen
// themselves, so the opening spring's give shows as the sticker swelling past full width and settling.
.modifier(Opening(width: shown ? size.width : size.height, radius: shown ? radius : size.height / 2, size: size, rim: rim, rimColor: style.rimColor))
.animation(frameIn, value: open)
// Held, it lifts off the page: a deeper, softer shadow. It doesn't move, so it stays under Reduce Motion.
.shadow(color: .black.opacity(pressed ? 0.26 : 0.14), radius: size.height * (pressed ? 0.24 : 0.1), y: size.height * (pressed ? 0.16 : 0.06))
// An overlay, so the marks reach past the frame without changing its layout. They contract onto the
// corners as they appear.
.overlay {
if style.cropMarks {
CropMarks(size: size)
.scaleEffect(marksShown ? 1 : 1.08)
.opacity(marksShown ? 1 : 0)
}
}
.opacity(open ? 1 : 0)
.animation(fadeIn, value: open)
.rotationEffect(.degrees(shown && !lift && !reduceMotion ? tilt : 0))
.animation(tiltIn, value: open)
// Peels up on the press spring, with no overshoot under the finger, and drops back to its tilt with
// a little give.
.scaleEffect(lift ? 1.18 : 1)
.animation(pressed ? motion.press : motion.release, value: pressed)
}
.task(id: open) {
// The landing beat, in time with the parent's tick: drift begins and the marks snap in, hold, then clear.
// Under Reduce Motion the fade is the landing; nothing drifts and the marks stay off.
guard open else { return }
try? await Task.sleep(for: .seconds(delay + PictureHeadline.landing(style, reduceMotion: reduceMotion)))
// A replay's outgoing copy never lands: no marks, no drift.
if Task.isCancelled || run.retired { return }
landedAt = .now
guard style.cropMarks, !reduceMotion else { return }
let motion = PieceMotion(reduceMotion: reduceMotion)
withAnimation(motion.snap) { marksShown = true }
try? await Task.sleep(for: .seconds(0.55))
withAnimation(motion.dismiss) { marksShown = false }
}
.onChange(of: reduceMotion) {
// Turning Reduce Motion off starts the drift again from its rest pose, rather than mid-swing.
if landedAt != nil { landedAt = .now }
}
}
@ViewBuilder private func content(_ size: CGSize) -> some View {
// Drift waits for the landing and stops under Reduce Motion, resting on time 0, each scene's designed pose.
let drifts = style.drift && PieceMotion(reduceMotion: reduceMotion).allowsAmbient
let start = drifts ? landedAt : nil
switch picture {
case .art(let scene):
TimelineView(.animation(minimumInterval: 1.0 / 30, paused: start == nil)) { context in
SceneArt(scene: scene, time: Self.driftTime(since: start, at: context.date))
}
case .image(let image):
TimelineView(.animation(minimumInterval: 1.0 / 30, paused: start == nil)) { context in
let t = Self.driftTime(since: start, at: context.date)
image
.resizable()
.scaledToFill()
.frame(width: size.width, height: size.height)
// Zoomed whenever it can drift, so the pan never shows an edge. The pan starts centred.
.scaleEffect(drifts ? 1.1 : 1)
.offset(x: sin(t * 0.35) * size.width * 0.03, y: sin(t * 0.27) * size.height * 0.03)
}
case .symbol(let name, let fill, let ink):
TimelineView(.animation(minimumInterval: 1.0 / 30, paused: start == nil)) { context in
let t = Self.driftTime(since: start, at: context.date)
ZStack {
fill
Image(systemName: name)
.font(.system(size: size.height * 0.5, weight: .semibold))
.foregroundStyle(ink)
.offset(y: sin(t * 1.4) * size.height * 0.04)
}
}
}
}
/// The sticker's frame and rim at `width`, centred in the slot. Past full width the picture swells with the
/// frame, so its edges never pull in from the rim; the slot's layout never moves.
private struct Opening: ViewModifier, Animatable {
var width: CGFloat
var radius: CGFloat
let size: CGSize
let rim: CGFloat
let rimColor: Color
nonisolated var animatableData: AnimatablePair<CGFloat, CGFloat> {
get { AnimatablePair(width, radius) }
set { width = newValue.first; radius = newValue.second }
}
func body(content: Content) -> some View {
let shape = RoundedRectangle(cornerRadius: max(0, radius), style: .continuous)
content
.scaleEffect(max(1, width / max(size.width, 1)))
.frame(width: max(0, width), height: size.height)
.clipShape(shape)
.overlay {
if rim > 0 { shape.strokeBorder(rimColor, lineWidth: rim) }
}
.frame(width: size.width, height: size.height)
}
}
/// Seconds of drift since landing, eased in over the first 0.8 s so a scene leaves its rest pose gently
/// instead of starting mid-swing. 0, the rest pose, until it lands.
private static func driftTime(since start: Date?, at date: Date) -> Double {
guard let start else { return 0 }
let t = max(0, date.timeIntervalSince(start)), ramp = 0.8
return t < ramp ? t * t / (2 * ramp) : t - ramp / 2
}
}
}
// MARK: - Crop marks
/// Four hairline crosses just outside a frame's corners, the marks the SwiftPieces site draws on its
/// dashed artboards. In the text colour, faint.
private struct CropMarks: View {
let size: CGSize
var body: some View {
let arm = max(3, size.height * 0.12)
let gap = max(3, size.height * 0.14)
Canvas { context, canvas in
let corners = [
CGPoint(x: -gap, y: -gap), CGPoint(x: size.width + gap, y: -gap),
CGPoint(x: -gap, y: size.height + gap), CGPoint(x: size.width + gap, y: size.height + gap),
]
var path = Path()
for c in corners {
let p = CGPoint(x: c.x + canvas.width / 2 - size.width / 2, y: c.y + canvas.height / 2 - size.height / 2)
path.move(to: CGPoint(x: p.x - arm, y: p.y)); path.addLine(to: CGPoint(x: p.x + arm, y: p.y))
path.move(to: CGPoint(x: p.x, y: p.y - arm)); path.addLine(to: CGPoint(x: p.x, y: p.y + arm))
}
context.stroke(path, with: .foreground, lineWidth: max(1, size.height * 0.025))
}
.frame(width: size.width + (gap + arm) * 2, height: size.height + (gap + arm) * 2)
.foregroundStyle(.primary.opacity(0.45))
.allowsHitTesting(false)
.accessibilityHidden(true)
}
}
// MARK: - Scenes
/// The built-in scenes, drawn with Canvas from the time so they loop without state.
private struct SceneArt: View {
let scene: PictureHeadline.Scene
let time: Double
var body: some View {
Canvas { context, size in
switch scene {
case .sun: sun(&context, size)
case .waves: waves(&context, size)
case .moon: moon(&context, size)
case .hills: hills(&context, size)
case .bloom: bloom(&context, size)
}
}
}
private func sun(_ c: inout GraphicsContext, _ s: CGSize) {
c.fill(Path(CGRect(origin: .zero, size: s)), with: .color(Art.butter))
// Our red mascot as the sun: it bobs, blinks now and then, and smiles over the sand.
let r = s.height * 0.3
let center = CGPoint(x: s.width * 0.6, y: s.height * 0.5 + sin(time * 0.7) * s.height * 0.05)
c.fill(Path(ellipseIn: CGRect(x: center.x - r, y: center.y - r, width: r * 2, height: r * 2)), with: .color(Art.red))
// The blink closes each 3.6 s cycle, so the rest pose at time 0 has its eyes open.
let blink = time.truncatingRemainder(dividingBy: 3.6) > 3.46 ? 0.2 : 1.0
for side in [-1.0, 1.0] {
let eye = CGPoint(x: center.x + side * r * 0.34, y: center.y - r * 0.12)
let w = r * 0.13, h = r * 0.2 * blink
c.fill(Path(ellipseIn: CGRect(x: eye.x - w, y: eye.y - h, width: w * 2, height: h * 2)), with: .color(Art.ink))
}
var smile = Path()
smile.addArc(center: CGPoint(x: center.x, y: center.y + r * 0.02), radius: r * 0.36, startAngle: .degrees(25), endAngle: .degrees(155), clockwise: false)
c.stroke(smile, with: .color(Art.ink), style: StrokeStyle(lineWidth: max(1, r * 0.11), lineCap: .round))
let horizon = s.height * 0.76
c.fill(Path(CGRect(x: 0, y: horizon, width: s.width, height: s.height - horizon)), with: .color(Art.sand))
// Glints on the sand, drifting.
for k in 0..<3 {
let w = s.width * (0.18 - Double(k) * 0.04)
let x = (s.width * (0.15 + Double(k) * 0.3) + time * 6).truncatingRemainder(dividingBy: s.width + w) - w
let y = horizon + s.height * (0.07 + Double(k) * 0.05)
c.fill(Path(roundedRect: CGRect(x: x, y: y, width: w, height: max(1, s.height * 0.03)), cornerRadius: s.height * 0.015), with: .color(Art.red.opacity(0.35)))
}
}
private func waves(_ c: inout GraphicsContext, _ s: CGSize) {
c.fill(Path(CGRect(origin: .zero, size: s)), with: .color(Art.sky))
let bands: [(Color, CGFloat, Double)] = [(Art.deepSky, 0.42, 0.9), (.white.opacity(0.85), 0.62, -1.2), (Art.deepSky.opacity(0.9), 0.8, 1.5)]
for (color, level, speed) in bands {
var path = Path()
let amplitude = s.height * 0.07
let wave = s.width * 0.55
path.move(to: CGPoint(x: 0, y: s.height))
for x in stride(from: 0.0, through: s.width, by: 2) {
path.addLine(to: CGPoint(x: x, y: s.height * level + sin((x / wave) * .pi * 2 + time * speed) * amplitude))
}
path.addLine(to: CGPoint(x: s.width, y: s.height))
path.closeSubpath()
c.fill(path, with: .color(color))
}
}
private func moon(_ c: inout GraphicsContext, _ s: CGSize) {
c.fill(Path(CGRect(origin: .zero, size: s)), with: .color(Art.night))
let stars: [(CGFloat, CGFloat, Double)] = [(0.12, 0.3, 0), (0.28, 0.72, 1.3), (0.42, 0.2, 2.1), (0.8, 0.78, 0.7), (0.9, 0.3, 2.8), (0.2, 0.52, 3.6)]
for (x, y, phase) in stars {
let r = s.height * 0.035 * (0.6 + 0.4 * (0.5 + 0.5 * sin(time * 1.6 + phase)))
c.fill(Path(ellipseIn: CGRect(x: s.width * x - r, y: s.height * y - r, width: r * 2, height: r * 2)), with: .color(.white.opacity(0.5 + 0.5 * (0.5 + 0.5 * sin(time * 1.6 + phase)))))
}
let r = s.height * 0.32
let center = CGPoint(x: s.width * 0.6, y: s.height * 0.5 + sin(time * 0.5) * s.height * 0.04)
c.fill(Path(ellipseIn: CGRect(x: center.x - r, y: center.y - r, width: r * 2, height: r * 2)), with: .color(Art.butter))
let bite = CGPoint(x: center.x + r * 0.45, y: center.y - r * 0.25)
c.fill(Path(ellipseIn: CGRect(x: bite.x - r * 0.9, y: bite.y - r * 0.9, width: r * 1.8, height: r * 1.8)), with: .color(Art.night))
}
private func hills(_ c: inout GraphicsContext, _ s: CGSize) {
c.fill(Path(CGRect(origin: .zero, size: s)), with: .color(Art.paleSage))
let r = s.height * 0.16
c.fill(Path(ellipseIn: CGRect(x: s.width * 0.74 - r, y: s.height * 0.3 - r, width: r * 2, height: r * 2)), with: .color(Art.butter))
let layers: [(Color, CGFloat, CGFloat, Double)] = [(Art.sage, 0.55, 0.16, 5), (Art.deepSage, 0.74, 0.12, 11)]
for (color, level, amplitude, speed) in layers {
var path = Path()
let wave = s.width * 0.9
path.move(to: CGPoint(x: 0, y: s.height))
for x in stride(from: 0.0, through: s.width, by: 2) {
let phase = (x + time * speed) / wave * .pi * 2
path.addLine(to: CGPoint(x: x, y: s.height * level - (sin(phase) * 0.5 + 0.5) * s.height * amplitude))
}
path.addLine(to: CGPoint(x: s.width, y: s.height))
path.closeSubpath()
c.fill(path, with: .color(color))
}
}
private func bloom(_ c: inout GraphicsContext, _ s: CGSize) {
c.fill(Path(CGRect(origin: .zero, size: s)), with: .color(Art.lilac))
let center = CGPoint(x: s.width * 0.5, y: s.height * 0.5)
let petal = s.height * 0.3
var turned = c
turned.translateBy(x: center.x, y: center.y)
turned.rotate(by: .radians(time * 0.4))
for k in 0..<6 {
var leaf = turned
leaf.rotate(by: .degrees(Double(k) * 60))
leaf.fill(Path(ellipseIn: CGRect(x: -petal * 0.32, y: -petal * 1.2, width: petal * 0.64, height: petal)), with: .color(.white.opacity(0.92)))
}
let core = s.height * 0.12
c.fill(Path(ellipseIn: CGRect(x: center.x - core, y: center.y - core, width: core * 2, height: core * 2)), with: .color(Art.butter))
}
}
/// House palette for the scenes (mirrors the web previews' blocks).
private enum Art {
static let butter = Color(red: 1, green: 0.761, blue: 0.102)
static let sand = Color(red: 1, green: 0.541, blue: 0.122)
static let red = Color(red: 1, green: 0.231, blue: 0.188)
static let sky = Color(red: 0.18, green: 0.545, blue: 1)
static let deepSky = Color(red: 0.31, green: 0.52, blue: 0.95)
static let paleSage = Color(red: 0.86, green: 0.95, blue: 0.88)
static let sage = Color(red: 0, green: 0.769, blue: 0.655)
static let deepSage = Color(red: 0.36, green: 0.66, blue: 0.46)
static let lilac = Color(red: 1, green: 0, blue: 0.361)
/// The moon's sky: a deep blue, so the frame reads on dark grounds as well as light.
static let night = Color(red: 0.149, green: 0.184, blue: 0.369)
static let ink = Color(red: 0.078, green: 0.078, blue: 0.078)
}
// MARK: - Layout
/// Sizes a picture from the line it sits in: its first subview is a hidden line of text in the current
/// font, which gives the line height; the frame is `height` of that line tall and `width` frames wide.
private struct PictureSlot: Layout {
var width: CGFloat
var height: CGFloat
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let line = subviews.first?.sizeThatFits(.unspecified).height ?? 0
return CGSize(width: (line * height * width).rounded(), height: line)
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
guard subviews.count > 1 else { return }
let line = bounds.height
let frame = CGSize(width: bounds.width, height: (line * height).rounded())
subviews[0].place(at: bounds.origin, proposal: ProposedViewSize(width: 0, height: line))
// Centred on the line, nudged down a touch to sit on the text's optical middle.
let y = bounds.minY + (line - frame.height) / 2 + line * 0.03
subviews[1].place(at: CGPoint(x: bounds.minX, y: y), proposal: ProposedViewSize(frame))
}
}
/// Wraps words and pictures into rows the way text wraps. The gap follows the row height, so it follows the font.
private struct HeadlineFlow: Layout {
var alignment: TextAlignment
private struct Row { var indices: [Int] = []; var width: CGFloat = 0; var height: CGFloat = 0 }
private func rows(for sizes: [CGSize], width: CGFloat) -> [Row] {
let gap = ((sizes.map(\.height).max() ?? 0) * 0.24).rounded()
var rows: [Row] = []
var row = Row()
for (i, size) in sizes.enumerated() {
let extended = row.indices.isEmpty ? size.width : row.width + gap + size.width
if extended > width, !row.indices.isEmpty {
rows.append(row)
row = Row()
}
row.width = row.indices.isEmpty ? size.width : row.width + gap + size.width
row.height = max(row.height, size.height)
row.indices.append(i)
}
if !row.indices.isEmpty { rows.append(row) }
return rows
}
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let sizes = subviews.map { $0.sizeThatFits(.unspecified) }
let rows = rows(for: sizes, width: proposal.width ?? .infinity)
let spacing = rowSpacing(sizes)
return CGSize(width: rows.map(\.width).max() ?? 0, height: rows.reduce(0) { $0 + $1.height } + spacing * CGFloat(max(0, rows.count - 1)))
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
let sizes = subviews.map { $0.sizeThatFits(.unspecified) }
let rows = rows(for: sizes, width: bounds.width)
let gap = ((sizes.map(\.height).max() ?? 0) * 0.24).rounded()
let spacing = rowSpacing(sizes)
var y = bounds.minY
for row in rows {
var x: CGFloat
switch alignment {
case .leading: x = bounds.minX
case .center: x = bounds.minX + (bounds.width - row.width) / 2
case .trailing: x = bounds.maxX - row.width
}
for i in row.indices {
subviews[i].place(at: CGPoint(x: x, y: y + row.height - sizes[i].height), proposal: .unspecified)
x += sizes[i].width + gap
}
y += row.height + spacing
}
}
/// A little air between rows, so pictures on neighbouring rows never touch.
private func rowSpacing(_ sizes: [CGSize]) -> CGFloat {
((sizes.map(\.height).max() ?? 0) * 0.06).rounded()
}
}
// MARK: - Example
/// The component alone: a centred headline with three of the built-in scenes opening between its
/// words, replaying every few seconds. Nothing around it.
private struct PictureHeadlineExample: View {
@State private var replay = 0
var body: some View {
PictureHeadline(
["Slow", .art(.sun, label: "a sunrise"), "mornings, long", .art(.waves, label: "the sea"), "walks and", .art(.hills, width: 1.8, label: "hills"), "early", .art(.moon, label: "the moon"), "nights."],
alignment: .center,
trigger: replay
)
.font(.system(size: 40, weight: .semibold))
.tracking(-1.2)
.foregroundStyle(PictureHeadlinePalette.text)
.frame(maxWidth: 360)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(PictureHeadlinePalette.ground)
.task {
while !Task.isCancelled {
try? await Task.sleep(for: .seconds(5.5))
replay += 1
}
}
}
}
/// House palette values for the example, adapting to light and dark.
private enum PictureHeadlinePalette {
static let ground = adaptive(light: 0xF3F2EE, dark: 0x121212)
static let text = adaptive(light: 0x141414, dark: 0xF4F3EF)
private static func adaptive(light: UInt32, dark: UInt32) -> Color {
Color(UIColor { @Sendable traits in
let hex = traits.userInterfaceStyle == .dark ? dark : light
return UIColor(red: CGFloat(hex >> 16 & 0xFF) / 255, green: CGFloat(hex >> 8 & 0xFF) / 255, blue: CGFloat(hex & 0xFF) / 255, alpha: 1)
})
}
}
#Preview("Light") {
PictureHeadlineExample()
.preferredColorScheme(.light)
}
#Preview("Dark") {
PictureHeadlineExample()
.preferredColorScheme(.dark)
}
// MARK: - Piece motion
//
// The SwiftPieces motion language: shared spring tokens and gesture physics, with the same values in every
// piece. Each piece carries a copy of only the parts it uses, so this file stands alone. Generated from
// registry/foundation/PieceMotion.swift in the SwiftPieces repo; edit it there, not here.
// swiftpieces-motion: 1.1.0 (core, follow)
/// The SwiftPieces motion language: five spring tiers, and a named role for every moment a piece moves,
/// each with its Reduce Motion substitute.
///
/// Build one from the environment, `PieceMotion(reduceMotion: reduceMotion)`, and pick the role that names
/// what just happened. Never animate the tracking of a finger: set gesture state directly in `onChanged`, so the
/// surface stays under the finger, and spring only the release.
private struct PieceMotion {
var reduceMotion = false
// Tiers. Overshoot and settle times are measured from rest with SwiftUI's Spring.
/// No overshoot, 90% in about 90ms. A press arriving under the finger.
static var tight: Spring { Spring(duration: 0.14, bounce: 0) }
/// About 2.8% overshoot, 90% in about 140ms. Snapping to a detent, page or segment.
static var responsive: Spring { Spring(duration: 0.32, bounce: 0.25) }
/// About 8.4% overshoot. Visible give: a release, a return from past an edge, a drag settling home.
static var elastic: Spring { Spring(duration: 0.42, bounce: 0.38) }
/// About 15% overshoot. A resolved action landing. At most once per interaction.
static var expressive: Spring { Spring(duration: 0.48, bounce: 0.48) }
/// About 1.5% overshoot, unhurried. Opening large surfaces and ambient change.
static var calm: Spring { Spring(duration: 0.5, bounce: 0.2) }
/// Reduce Motion: settles become this short spring with no overshoot.
private static var still: Animation { .spring(duration: 0.25, bounce: 0) }
// Roles.
/// Touch-down. Starts on the same frame and never bounces under the finger.
var press: Animation { .spring(Self.tight) }
/// The finger lifts off a pressed surface, which springs back through rest.
var release: Animation { reduceMotion ? Self.still : .spring(Self.elastic) }
/// A dragged thing comes to rest. With a gesture's velocity, use `settle(velocity:from:to:)` instead.
var settle: Animation { reduceMotion ? Self.still : .spring(Self.elastic) }
/// Lands on a detent, page or segment.
var snap: Animation { reduceMotion ? Self.still : .spring(Self.responsive) }
/// A number, a chart value or anything else people read moves to its new value. Never overshoots, so it
/// never shows a value that isn't true.
var value: Animation { reduceMotion ? Self.still : .spring(duration: 0.35, bounce: 0) }
/// Comes back from past a limit: a pull beyond the edge, a value pushed against its bound.
var rebound: Animation { reduceMotion ? Self.still : .spring(Self.elastic) }
/// A shape or container changes size, corner radius or form, with a little give at the end.
var morph: Animation { reduceMotion ? Self.still : .spring(duration: 0.4, bounce: 0.2) }
/// Something appears, opens or expands. Opening is a little slower than closing.
var reveal: Animation { reduceMotion ? .easeOut(duration: 0.2) : .spring(Self.calm) }
/// Something leaves, closes or collapses. Quick and firm, out of the way.
var dismiss: Animation { reduceMotion ? .easeIn(duration: 0.18) : .spring(duration: 0.3, bounce: 0.08) }
/// A resolved action lands: a check, a sent state, a reaction.
var success: Animation { reduceMotion ? .easeOut(duration: 0.24) : .spring(Self.expressive) }
/// A refused action. Firm, no wobble; `pieceShake` adds the movement.
var error: Animation { reduceMotion ? .easeOut(duration: 0.2) : .spring(Self.responsive) }
/// Slow ambient change. Loops themselves stop under Reduce Motion: check `allowsAmbient`.
var ambient: Animation { reduceMotion ? .easeInOut(duration: 0.3) : .spring(Self.calm) }
/// Loops, drifts, idle breathing and parallax run only when this is true.
var allowsAmbient: Bool { !reduceMotion }
/// A moving transition, or a plain fade under Reduce Motion.
func transition(_ transition: AnyTransition) -> AnyTransition {
reduceMotion ? .opacity : transition
}
/// For content replaced inside a container that stays put (a label, a glyph, a count): the old content
/// blurs out as the new one sharpens in. A fade under Reduce Motion.
@MainActor var swap: AnyTransition {
reduceMotion ? .opacity : AnyTransition(.blurReplace)
}
}
extension PieceMotion {
/// Follow-through: rank 0 leads, each later rank arrives a beat later on a slightly looser spring. Safe to reverse.
func follow(_ spring: Spring = PieceMotion.elastic, rank: Int) -> Animation {
guard !reduceMotion else { return .spring(duration: 0.25, bounce: 0) }
let k = Double(min(max(rank, 0), 6))
return .spring(duration: spring.duration + 0.04 * k, bounce: min(spring.bounce + 0.02 * k, 0.55))
}
/// One-shot entrances only: item `index` waits 30ms per place, capped at the seventh. Exits go together.
func cascade(_ animation: Animation, index: Int, step: Double = 0.03) -> Animation {
guard !reduceMotion, index > 0 else { return animation }
return animation.delay(step * Double(min(index, 7)))
}
}
// swiftpieces-motion: end- Type
- PictureHeadline
- Files
- PictureHeadline.swift
- Depends on
- Nothing (Apple frameworks only)
- Version
- 1.2.0
A headline with pictures stuck between its words like stickers, revealed in reading order. Write it as a list of segments: strings are words, pictures sit where you put them. swift PictureHeadline(["Slow", .art(.sun), "mornings, long", .art(.waves), "walks and early", .art(.moon), "nights."]) .font(.system(size: 40, weight: .semibold)) Words are set in the house weight, semibold. Pictures are sized from the font, so they follow Dynamic Type and every font you set. Each lands as a sticker: a white rim, a soft shadow and a small tilt that alternates along the headline, with crop marks flashing at its corners. Press and hold one to lift it. Text wraps word by word and a picture never breaks from the row it lands on.
Notes
- Write the headline as a list: string literals are words and pictures go where you put them, for example
["Slow", .art(.sun), "mornings, long", .art(.waves), "walks."]. A string can hold several words; each word rises on its own. - Pictures land as stickers: a white rim, a soft shadow and a small resting tilt that alternates along the headline (
Style.tilt, 4 degrees at most), so a line reads as placed by hand. As each one lands, four hairline crop marks snap in at its corners, contracting onto them, and clear a moment later: the crosses SwiftPieces draws on its artboards.Style.tilt = 0lays them flat,Style.rim = 0drops the rim andStyle.cropMarks = falseskips the marks. - Press and hold a sticker to lift it: it peels up at once on a spring with no overshoot under the finger, straightening and scaling up with a deeper shadow above its neighbours. A light tick lands once the hold has lasted a moment, so a quick tap or a scroll that starts on a sticker stays silent. It stays up until you let go, then drops back to its tilt with a little give. The press uses
onLongPressGesture(onPressingChanged:)with a small tolerance, so scrolling over the headline still scrolls. A hold claims the touch, so a headline inside aButtonor a tappable card doesn't also trigger it; a quick tap still passes through.Style.lifts = falseturns the lift off. - Words are set in the house weight, semibold, at the piece's root; size carries the hierarchy, as the example's
.font(.system(size: 40, weight: .semibold))shows. - Pictures are sized from the font:
Style.pictureHeightis a fraction of the line height (0.82 by default) and each picture'swidthis in picture heights (2.4 is a wide frame, 1 a square). Set the font with.font(...)as usual and the pictures follow it, Dynamic Type included. - Words and pictures wrap like text with a private
Layout, so the headline breaks across rows at any width and a picture never splits from the row it lands on.alignmentsets each row's alignment. - The reveal runs in reading order. Each word slides up from behind its own baseline on a calm spring that never overshoots. Each picture appears as a dot as tall as the frame and widens into the full sticker on the opening spring (
Style.openDurationandStyle.openBounce), swelling a little past full width, picture and rim together, before it settles; its tilt lands a beat behind the frame as follow-through, and its contents settle from a slight zoom just after the frame lands. The stagger is sized from the number of items, so a short and a long headline both land in aboutduration(1.2 seconds by default).delayholds the start; changetriggerto replay. The old headline fades out with the words it was showing, and the new one rises a beat behind it, so changing the segments and the trigger together (a pager, say) moves from one headline to the next without a cut. - Three kinds of picture:
.art(_:)draws one of five built-in scenes in the house palette (.sunis the red SwiftPieces mascot, bobbing and blinking over the sand;.waves,.moon,.hillsand.bloom), so a headline looks finished before you have artwork;.image(_:)fills the frame with your ownImage;.symbol(_:fill:ink:)sets an SF Symbol on a solid block. - After landing, pictures keep moving: each starts from a still rest pose as it lands and eases into its drift over about a second, each on its own clock. Scenes drift (the sun bobs and blinks, the sea slides, stars twinkle), images pan slowly and symbols bob. Set
Style.drift = falsefor still pictures. Drawing usesCanvasdriven by aTimelineViewat up to 30 frames a second, paused until the picture lands. revealOnScrollwaits until the headline scrolls into view withonScrollVisibilityChangeon iOS 18; on iOS 17 it reveals on appear.- Haptics: a light tick as each picture's frame lands, timed from the opening spring and on the beat of its crop marks, and another when a hold lifts one. Under Reduce Motion one tick marks the moment the headline has faded in. A headline fading out for a replay never ticks. Pass
haptics: falseto stay silent. - VoiceOver reads the headline as one header: the words in order, plus a picture's
labelwhere it sits, so.art(.sun, label: "a sunrise")is read and an unlabelled picture is skipped. - Reduce Motion keeps the feedback and drops the movement: words and pictures fade in together, and pictures sit flat and still on their rest pose (the sun with its eyes open), with no rise, zoom, tilt, crop marks or drift. A held sticker deepens its shadow and shifts its brightness slightly instead of lifting (darker in light mode, lighter in dark mode), one tick marks the landing, and a replay fades the old headline out just ahead of the new one fading in.
Style(.standardis the house look):pictureHeight,cornerRadius(a fraction of the picture height; 0.5 makes a capsule),tilt,rim,rimColor,cropMarks,lifts,drift,openDurationandopenBounce.
Usage
PictureHeadlineExample()
.preferredColorScheme(.light)Parameters
| Parameter | Description |
|---|---|
segments | Words (string literals) and pictures (.art, .image, .symbol), in reading order. |
alignment | Row alignment, like multilineTextAlignment. |
duration | Target time for the whole reveal, in seconds. The stagger is sized from the number of words and pictures, so short and long headlines both land in about this long. |
delay | Delay before the first word starts. |
revealOnScroll | When true, the reveal waits until the headline scrolls into view (iOS 18). Below iOS 18 it reveals on appear. |
trigger | Change this value to replay the reveal. |
haptics | A light tick as each picture lands and when one is lifted. On by default. |
style | Picture size, corner rounding, tilt, rim, crop marks, lifting, drift and the opening spring. |
Install
Pick one. Run it from the folder that contains your .xcodeproj and the files land inside your app.
Terminal
Or ask your coding agent · Claude Code, Cursor or Xcode, once the MCP server is connected
Or copy the source above into your app.
New to SwiftUI?If you know React, CSS or Tailwind, SwiftUI is easier to pick up than it looks.Try real app patterns first
Building a whole app? See SwiftPieces Pro →
More SwiftUI text
All text →Build it yourself: SwiftUI animations guide · Liquid Glass guide









