본문 바로가기

iOS/STUDY

[iOS] CAGradientLayer (그라데이션 배경)

https://developer.apple.com/tutorials/app-dev-training/creating-a-gradient-background

 

Apple Developer Documentation

 

developer.apple.com

iOS App Dev Tutorials

끝이 보이네요! 

 

이번엔 그라데이션 배경을 만드는 방법에 대해 알아보겠습니다.

 

 

segment (Today, Future, All) 마다 그라데이션 색상을 다르게 적용해볼 것입니다.

 

우선 사용할 CAGradientLayer 에 대해 알아보겠습니다.

 

 

CAGradientLayer

A layer that draws a color gradient over its background color, filling the shape of the layer (including rounded corners)
배경색 위에 그라데이션 색상을 그려 레이어의 모양을 채우는 레이어 (둥근 모서리 포함)

이름 그대로 배경에 레이어 형식으로 그라데이션을 입힌다고 생각하면 될 것 같네요.

 

Declaration

class CAGradientLayer : CALayer

 

CAGradientLayer를 사용하여 임의의 색상 수를 포함하는 그라디언트 레이어를 만듭니다.

기본적으로 균일하게 분포되지만 선택적으로 색상 위치를 제어할 수 있습니다.

 

임의의 색상 수를 포함한다는 소리는 아래와 같이 배열의 형태로 여러가지 색상을 전달할 수 있습니다.

gradientLayer.colors = [UIColor.red.cgColor,
                        UIColor.yellow.cgColor,
                        UIColor.green.cgColor,
                        UIColor.blue.cgColor]

그리고 위치를 조정해줄 수도 있습니다.

gradientLayer.transform = CATransform3DMakeRotation(CGFloat.pi / 2, 0, 0, 1)

 

 

 

UICollectionViewController 에 그라데이션 배경 적용

리스트 스타일에 따라서 (today, future, all) 배경색을 다르게 지정해줄 것이기 때문에

CAGradientLayer+ListStyle.swift 파일을 생성해서 style에 따라 다른 CAGradientLayer 를 리턴해줄 것입니다.

 

두가지 색상으로 그라데이션을 할 것이기 때문에 색상은 두가지, 이 색상을 적용할 frame 을 적용하여 레이어를 반환합니다.

extension CAGradientLayer {
    static func gradientLayer(for style: ReminderListStyle, in frame: CGRect) -> Self {
        let layer = Self()
        layer.colors = colors(for: style)
        layer.frame = frame
        return layer
    }
    
    private static func colors(for style: ReminderListStyle) -> [CGColor] {
        let beginColor: UIColor
        let endColor: UIColor
        
        switch style {
        case .all:
            beginColor = .todayGradientAllBegin
            endColor = .todayGradientAllEnd
        case .future:
            beginColor = .todayGradientFutureBegin
            endColor = .todayGradientFutureEnd
        case .today:
            beginColor = .todayGradientTodayBegin
            endColor = .todayGradientTodayEnd
        }
        return [beginColor.cgColor, endColor.cgColor]
    }
}

 

그리고 CollectionViewController 에서 배경색을 지정해주어야합니다.

 

1. collectionView 의 backgroundView 를 초기화합니다.

2. 새로운 UIView 를 생성합니다.

3. 리스트 스타일, collectionView 의 frame 에 맞게 CAGradientLayer 를 생성합니다.

4. UIView 의 레이어에 addSublayer() 로 3에서 만든 레이어를 적용합니다.

5. 만든 UIView 를 collectionView 의 backgroundView 에 적용합니다.

 

func refreshBackground() {
    collectionView.backgroundView = nil
    let backgroundView = UIView()
    var graientLayer = CAGradientLayer.gradientLayer(for: listStyle, in: collectionView.frame)
    backgroundView.layer.addSublayer(graientLayer)
    collectionView.backgroundView = backgroundView
}

 

 

그리고 적절한 위치에서 (viewWillApear(_:)) 호출해주면 됩니다.

segment 가 바뀔 때마다도 호출되어야 하니 segment 버튼이 눌릴 때마다에도 호출해줍니다.