[swift] Swift Core Graphics로 그라데이션 배경 만들기
Swift에서 Core Graphics를 사용하면 그라데이션 배경을 만들 수 있습니다.
1. UIView를 서브 클래스로 만들기
Core Graphics를 사용하여 그라데이션 배경을 만들기 위해 당신은 UIView
를 서브 클래스로 만들어야 합니다.
import UIKit
class GradientView: UIView {
// 그라데이션을 그리는 코드를 여기에 추가할 것입니다.
}
2. draw(_:) 메서드 구현하기
draw(_:)
메서드를 구현하여 Core Graphics를 사용하여 그라데이션을 그릴 수 있습니다.
import UIKit
class GradientView: UIView {
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let colorSpace = CGColorSpaceCreateDeviceRGB()
let startColor = UIColor.red.cgColor
let endColor = UIColor.green.cgColor
let colors = [startColor, endColor] as CFArray
let locations:[CGFloat] = [0.0, 1.0]
if let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: locations) {
context?.drawLinearGradient(gradient, start: CGPoint(x: 0, y: 0), end: CGPoint(x: self.bounds.width, y: self.bounds.height), options: [])
}
}
}
3. GradientView를 사용하여 뷰를 만들기
이제 GradientView를 사용하여 그라데이션 배경을 가진 뷰를 만들 수 있습니다.
let gradientView = GradientView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.addSubview(gradientView)
위의 코드를 사용하여 Core Graphics를 사용하여 Swift에서 그라데이션 배경을 만들 수 있습니다.
참고 문헌:
Apple Developer Documentation - Core Graphics NSHipster - Core Graphics