UIView Animation

Judy·2022년 10월 6일
0

iOS

목록 보기
21/28

UIView Animation

UIView란

화면의 직사각형 영역에 대한 콘텐츠를 관리하는 개체


Animate views

UIView의 프로퍼티를 조절해서 애니메이션 효과를 줄 수 있다.

UIView 프로퍼티

  • frame : 상위 뷰의 좌표를 기준으로 뷰의 위치와 크기를 나타내는 사각형
  • bounds : 자체 좌표로 뷰의 위피와 크기를 나타내는 사각형
  • center : 뷰 frame의 중심점
  • transform : 뷰의 bounds 중심을 기준으로 scale이나 rotate 변화를 나타냄
  • alpha : 뷰의 투명도
  • backgroundColor : 뷰의 배경 색상

1. animate

class func animate(
    withDuration duration: TimeInterval, // 애니메이션 시간
    delay: TimeInterval, // 애니메이션 시작 딜레이
    options: UIView.AnimationOptions = [], // 애니메이션 효과
    animations: @escaping () -> Void, // 뷰의 프로퍼티를 변경하는 코드
    completion: ((Bool) -> Void)? = nil // 애니메이션 완료 후 실행 코드
)
  • UIViewType Method

예시

UIView.animate(withDuration: 3, delay: 1, options: [.curveEaseInOut, .repeat]) {
    self.view.backgroundColor = .systemBlue
} completion: { isFinished in
    self.view.backgroundColor = .systemBackground
}
  • 1초 이후에 뷰의 배경색이 systemBlue로 변하는 애니메이션이 3초 동안 애니메이션이 실행 후 다시 systemBackground로 변함

2. animateKeyframes

class func animateKeyframes(
    withDuration duration: TimeInterval,
    delay: TimeInterval,
    options: UIView.KeyframeAnimationOptions = [],
    animations: @escaping () -> Void,
    completion: ((Bool) -> Void)? = nil
)
  • KeyFrame을 기반으로 애니메이션을 적용
  • KeyFrame : 시작과 마지막 프레임에서 중심이 되는(전체를 표현하는) 한 부분이 되는 프레임

addKeyframe

class func addKeyframe(
    withRelativeStartTime frameStartTime: Double, // 해당 애니메이션이 시작하는 시간을 전체 애니메이션 시간의 비율로 표시(0~1)
    relativeDuration frameDuration: Double, // 애니메이션이 진행되는 시간을 전체 애니메이션 시간의 비율로 표시(0~1)
    animations: @escaping () -> Void // 애니메이션 코드
)
  • addKeyframe 메서드로 특정 부분만 부분적으로 애니메이션을 줄 수 있음
  • 연속된 애니메이션을 표현하기에 적절

예시

UIView.animateKeyframes(withDuration: 3, delay: 0, options: .allowUserInteraction) {
    UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1/3) {
        self.view.frame = self.view.frame.offsetBy(dx: 50, dy: 50)
    }
    UIView.addKeyframe(withRelativeStartTime: 1/3, relativeDuration: 1) {
        self.view.backgroundColor = .red
    }
} completion: { isFinished in
    print(isFinished)
}
  • 전체 애니메이션 시간은 3초
  • 0초부터 1초까지 위치를 변경하는 애니메이션 실행
  • 1초부터 3초까지 배경 색상을 변경하는 애니메이션 실행



참고링크
UIView
animate
addKeyframe
animateKeyframes

profile
iOS Developer

0개의 댓글