As a path transition to a gradient that sets the colors out of the path ends

I want to draw a gradient path that is from a color at the beginning and end of a different color .

Here are two ways to draw a gradient line, but no effect is needed.

Anyone have an idea to do this?

guard let c = UIGraphicsGetCurrentContext() else {
    fatalError("Current Context NOT Founds.")
}

c.setLineWidth(width)
c.setLineCap(cap)
c.setLineJoin(join)

// the way no.1
c.saveGState()
c.move(to: CGPoint(x: 50, y: 50))
c.addLine(to: CGPoint(x: 50, y: 200))
c.addLine(to: CGPoint(x: 150, y: 200))
let alphas: [CGFloat] = [0, 1]
let colors = [UIColor(white: 1, alpha: alphas[0]).cgColor, UIColor(white: 1, alpha: alphas[1]).cgColor] as CFArray
let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors, locations: [0.0, 1.0])
c.addRect(.infinite)
c.replacePathWithStrokedPath()
c.clip()
c.drawLinearGradient(gradient!, start: CGPoint(x: 0, y: 0), end: CGPoint(x: rect.width, y: rect.height), options: CGGradientDrawingOptions(rawValue: 0))
c.restoreGState()

// the way no.2
c.saveGState()
c.beginTransparencyLayer(in: rect, auxiliaryInfo: nil)
c.move(to: CGPoint(x: 50, y: 250))
c.addLine(to: CGPoint(x: 50, y: 450))
c.addLine(to: CGPoint(x: 130, y: 350))
c.setStrokeColor(UIColor.white.cgColor)
c.strokePath()
c.setBlendMode(.sourceIn)
c.drawLinearGradient(gradient!, start: CGPoint(x: 50, y: 220), end: CGPoint(x: 50, y: 450), options: CGGradientDrawingOptions(rawValue: 0))
c.endTransparencyLayer()
c.restoreGState()

      

sample


last update 2017/05/26

Here are some sample images that are similar to what I want.

sample1

sample2

sample3

+3


source to share





All Articles