iOS

[iOS/Swift] UIView, UILabel에 그라데이션 색깔 적용 Extension

meenyweeny 2022. 3. 14. 10:10

프로젝트 하다가 그라데이션 색을 적용할 일이 많아서.. 익스텐션이 필요해서 만들어보았다

사실 만든건 아니고 하나의 Extension으로 합친거긴 하지만,,!

 

참고로 Extension이라는 것은..

extension UIView {

          함수 구현

}

이런 식으로

이 안에 함수를 넣어주어 UIView나 UILabel에 있는 기본 메서드들 처럼 사용할 수 있게 넣어주는걸 말한다..

한번만 쓴다면 굳이 그렇게 할 필요 없지만, 앱 내에서 자주 쓰이는 기능이라면 편하게 하기 위함이다


View에 Gradient Color 적용 Extension

 

코드

    func setViewGradient(startColor: UIColor, endColor: UIColor) {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.colors = [startColor.cgColor, endColor.cgColor]
        gradient.locations = [0.0, 1.0]
        gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
        gradient.frame = bounds
        layer.addSublayer(gradient)
    }

사용 방법

myView.setViewGradient(startColor: .black, endColor: .brown)

 


Label에 Gradient Color 적용 Extension

 

코드

    func setLabelGradientColor(startColor: UIColor, endColor: UIColor) {
        let gradient = CAGradientLayer()
        gradient.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 200)
        gradient.colors = [startColor.cgColor, endColor.cgColor]
        gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
        
        UIGraphicsBeginImageContextWithOptions(gradient.bounds.size, false, 0.0)
        gradient.render(in: UIGraphicsGetCurrentContext()!)
        let makeImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        self.textColor = UIColor(patternImage: makeImage!)
    }

 

사용 방법

myLabel.setLabelGradientColor(startColor: .black, endColor: .brown)

 


주의 사항

 

지금 현재 내가 적용할 UIView나 UILabel의 실제 width에 맞춰 그라데이션 시작과 끝 위치가 적용이 된다. (frame의 width)

예를 들어, storyboard에서 UILabel의 text가 Label인 기본 Label 하나를 추가해두고,

ViewController 파일에서 label.text = "안녕하세요안녕하세요" 이렇게만 바꿨을 때, 길어진 width에 대해

UILabel이 스스로 모르는 상태라면 그라데이션의 시작과 끝 위치가 제대로 적용이 안되어 원하는 결과를 얻을 수 없다.

그러니 잘 알려준 상태에서 써야한다,,!

(그러니 당연히 데이터에 따라 값이 바뀌지 않는 경우의 UIView나 UILabel 같은 경우에는 이런 작업이 필요하지 않다)

 


View Gradient 참고 블로그

https://fomaios.tistory.com/entry/UIView-백그라운드-그라데이션-색-넣기-UIView-Background-gradient-color

 

[iOS/UI] UIView 백그라운드 그라데이션 색 넣기 (UIView Background gradient color)

오늘은 UIView에 그라데이션 색 효과넣는 법을 알아봅시다. 제일 먼저 스토리보드에서 시험하기 위한 view를 하나 만들어주고 뷰컨트롤러에 연결시켜줍니다. 그런 다음 extension으로 UIView를 확장시

fomaios.tistory.com

Label Gradient 참고 블로그

https://ios-development.tistory.com/394

 

[iOS - swift] CAGradientLayer, layer.mask (+ 텍스트 gradient fade out 처리)

CAGradientLayer이란? layer에 색 그라데이션을 입히는데 사용되는 객체 주로 UIView나 UILabel의 text에 그라데이션을 입히는데 사용 CAGradientLayer 사용 방법 객체 생성 후 frame 설정: frame은 적용될 view..

ios-development.tistory.com