fs_tigre
fs_tigre

Reputation: 10748

Understanding scaleEffect in SwiftUI

The following code animates the size of an image as soon as it loads, it animates it from half of its size to its full size, but there is something I don't fully understand about the parameters in scaleFactor.

Can someone explain the parameter inside the scaleEffect modifier?

  1. How come it can take a Boolean parameter?
  2. How is it possible to enter a scale range 1.0 : 0.5 parameter?
  3. What does the ? do?

As far as I can see the scaleEffect modifier only takes two parameters, a CGFloat and a UnitPoint.

struct ContentView: View {
    @State private var scaleFactor = false
    var body: some View {
        VStack {
            Image("top-image")
                .scaleEffect(scaleFactor ? 1.0 : 0.5)
                .animation(.easeInOut(duration: 1.0))
                .onAppear() {
                    self.scaleFactor = true
                }
        }
    }
}

Upvotes: 3

Views: 4732

Answers (1)

Asperi
Asperi

Reputation: 258117

There are several declared overloaded scaleEffect

extension View {

    @inlinable public func scaleEffect(_ scale: CGSize, anchor: UnitPoint = .center) -> some View

    @inlinable public func scaleEffect(_ s: CGFloat, anchor: UnitPoint = .center) -> some View

    @inlinable public func scaleEffect(x: CGFloat = 0.0, y: CGFloat = 0.0, anchor: UnitPoint = .center) -> some View
}

In the example in question it is used second one, so it is actually

        Image("top-image")
            .scaleEffect(scaleFactor ? 1.0 : 0.5, anchor: .center)

which is documented as

Scales this view’s rendered output by the given amount in both the horizontal and vertical directions, relative to an anchor point.

and scaleFactor ? 1.0 : 0.5 means just in-place ternary operator for first scale parameter which applied either 1.0 (identity) or 0.5 (half) depending on corresponding view state.

Upvotes: 4

Related Questions