
먼저, Gradient Brush를 사용하여 배경을 gradient로 변경하는 코드에서 문제가 발생하는 이유는 UIDrawBrushGradient 클래스가 deprecated 되었기 때문입니다. 대신 CGGradient 클래스를 사용해야 합니다.
다음은 CGGradient 클래스를 사용하여 배경을 gradient로 변경하는 코드입니다.
#hostingforum.kr
swift
let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: [UIColor.red.cgColor, UIColor.blue.cgColor], locations: [0, 1])!
view.layer.backgroundColor = UIColor.clear.cgColor
view.layer.contents = UIGraphicsImageRenderer(size: view.bounds.size).image { _ in
UIGraphicsGetCurrentContext()!.scaleBy(x: 1, y: -1)
UIGraphicsGetCurrentContext()!.translateBy(x: 0, y: -view.bounds.height)
UIGraphicsGetCurrentContext()!.drawLinearGradient(gradient, start: CGPoint(x: 0, y: 0), end: CGPoint(x: 1, y: 0), options: [])
}
위의 코드를 실행하여 Gradient의 색상이 정상적으로 나타나게 됩니다.
addStop() 메서드를 사용하여 Gradient의 색상을 변경하는 방법은 다음과 같습니다.
#hostingforum.kr
swift
let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: [UIColor.red.cgColor, UIColor.blue.cgColor], locations: [0, 1])!
gradient.colors = [UIColor.red.cgColor, UIColor.green.cgColor, UIColor.blue.cgColor]
gradient.locations = [0, 0.5, 1]
view.layer.backgroundColor = UIColor.clear.cgColor
view.layer.contents = UIGraphicsImageRenderer(size: view.bounds.size).image { _ in
UIGraphicsGetCurrentContext()!.scaleBy(x: 1, y: -1)
UIGraphicsGetCurrentContext()!.translateBy(x: 0, y: -view.bounds.height)
UIGraphicsGetCurrentContext()!.drawLinearGradient(gradient, start: CGPoint(x: 0, y: 0), end: CGPoint(x: 1, y: 0), options: [])
}
위의 코드를 실행하여 Gradient의 색상이 정상적으로 나타나게 됩니다.
2025-07-10 22:11