Skip to content

Instantly share code, notes, and snippets.

@rumikotakahashi
Forked from williamhqs/GradientLine.swift
Created September 4, 2017 05:26
Show Gist options
  • Select an option

  • Save rumikotakahashi/4b11e6544d927a2eb694f6ecec3a7ac4 to your computer and use it in GitHub Desktop.

Select an option

Save rumikotakahashi/4b11e6544d927a2eb694f6ecec3a7ac4 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
@rumikotakahashi
Copy link
Copy Markdown
Author

Great information. Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment