Skip to content

Instantly share code, notes, and snippets.

@williamhqs
Last active December 12, 2019 22:08
Show Gist options
  • Save williamhqs/3ecea38fd4a15732f1b24991018be313 to your computer and use it in GitHub Desktop.
Save williamhqs/3ecea38fd4a15732f1b24991018be313 to your computer and use it in GitHub Desktop.
CoreGraphics draw a line with gradient and lineCap
class GradientLineView: UIView {
override func draw(_ rect: CGRect) {
if let context = UIGraphicsGetCurrentContext() {
let startPoint1 = CGPoint(x: 20, y: rect.height/2)
let endPoint1 = CGPoint(x: rect.width-120, y: rect.height/2)
context.setLineWidth(15)
context.move(to: startPoint1)
context.addLine(to: endPoint1)
context.setLineCap(.round)
context.setStrokeColor(UIColor.red.cgColor)
context.replacePathWithStrokedPath()
context.clip()
let startPoint2 = CGPoint(x: 0, y: rect.height/2)
let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: [UIColor.blue.cgColor, UIColor.green.cgColor] as CFArray, locations: [0.3, 0.7])
context.drawLinearGradient(gradient!, start: startPoint2, end: endPoint1, options: CGGradientDrawingOptions.drawsAfterEndLocation)
}
}
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = UIColor.clear
}
}
// Test in Playgoround
let v = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
v.backgroundColor = UIColor.white
let p = GradientLineView(frame: CGRect(x: 20, y: 20, width: 200, height: 50))
v.addSubview(p)
PlaygroundPage.current.liveView = v
PlaygroundPage.current.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment