Draw Radial Gradient iOS top half area of a UIView

764 views Asked by At
func drawRadialGradient(context:CGContext , rect:CGRect , startColor:UIColor , endColor:UIColor){

    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let colorComponents = [startColor.cgColor,endColor.cgColor] as CFArray
    let locations:[CGFloat] = [0.0,1.0]
    context.saveGState()
    if let gradient = CGGradient.init(colorsSpace: colorSpace, colors: colorComponents, locations: locations) {



        context.drawRadialGradient(gradient, startCenter: CGPoint(x:rect.midX,y:0), startRadius: 0, endCenter: CGPoint(x:rect.midX,y:0), endRadius: rect.midX, options: .drawsBeforeStartLocation)


    }
    context.restoreGState()
}

The above code has rect 0,0,width,totalViewheight/2.0. i.e the light orange color area. where totalViewheight=40.0

lightOrangeRect = CGRectMake(0,0,width,totalViewheight/2.0) i.e (0,0,414,20)

I want to draw a radial gradient touching points 
1) 0,0 i.e (0,0)
2) lightOrangeRect/2.0, lightOrangeRect.height i.e (207,20)
3) lightOrangeRect, 0 i.e (414,0)

So, as to give the glossy effect of the arc at the top half area (light orange color area).

enter image description here

1

There are 1 answers

0
NNikN On
context.drawRadialGradient

does not work here as it involves calculation for center, for a circle which passes through those points.

I found the following solution working for me. Draw the path, clip it and then we draw a linear gradient in it.

The code is as shown below.

func drawRadialGradient(context:CGContext,rect:CGRect,startColor:UIColor , endColor:UIColor){
    context.saveGState()

    context.beginPath()
    context.move(to: CGPoint(x: rect.maxX, y: 0))
    context.addQuadCurve(to: CGPoint.zero, control: CGPoint(x: rect.midX, y: rect.maxY))
    context.closePath()
    context.clip()
    //...Your....drawLinearGradient...code here.
    context.restoreGState()

}

The following results were achieved.

enter image description here