Aditya Rudrapatna
Aditya Rudrapatna

Reputation: 49

Core Graphics- Using CGGradient with strokes and text

So here is my code for creating a particular gradient:

     let newBlueOne = UIColor(red: 0.141, green: 0.776, blue: 0.863,     alpha: 1.000)
    let newBlueTwo = UIColor(red: 0.318, green: 0.290, blue: 0.616, alpha: 1.000)

And here is the code for the gradient itself:

let newBlue = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [newBlue1.CGColor, newBlue2.CGColor], [0, 1])!

Here is the code for the rectangle I'm trying to make:

      let rectanglePath = UIBezierPath(roundedRect: CGRect(x: 22, y: 35, width: 194, height: 38), cornerRadius: 19)
    CGContextSaveGState(context)
    rectanglePath.addClip()
    CGContextDrawLinearGradient(context, translucent1, CGPoint(x: 119, y: 35), CGPoint(x: 119, y: 73), CGGradientDrawingOptions())
    CGContextRestoreGState(context)
    rectanglePath.lineWidth = 1
    rectanglePath.stroke()

I want to use that newBlue gradient above as the stroke colour for this rectangle created. I also want to change the colour of some text to that newBlue gradient. Unfortunately, I can't quite figure it out. Can anyone help?

I appreciate your responses and look forward to reading them. Thank you so much :)

Upvotes: 1

Views: 654

Answers (1)

user3230875
user3230875

Reputation: 689

You can not directly stroke a path with a gradient.

To do what you want, you will need to go to the Core Graphics Layer, and use the CGContext Functions.

First, you create your path, and set its various properties, such as line weight.

Then, you use the CGContextReplacePathWithStrokedPath(context) function. Look it up in the CGContext documentation.

Then, you use the resultant path as a clip path.

And then, you paint that area with your gradient.

Like This:

override  func  drawRect(rect: CGRect) {
    let newBlueOne = UIColor(red: 0.141, green: 0.776, blue: 0.863, alpha: 1.000)
    let newBlueTwo = UIColor(red: 0.318, green: 0.290, blue: 0.616, alpha: 1.000)
    let newBlue = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [newBlueOne.CGColor, newBlueTwo.CGColor], [0, 1])!

    let  lineWeight: CGFloat = 20.0

    let  context: CGContext = UIGraphicsGetCurrentContext()!

    let  rect: CGRect = CGRectMake(40.0, 40.0, 200.0, 200.0)
    CGContextAddRect(context, rect)
    CGContextSetLineWidth(context, lineWeight)
    CGContextReplacePathWithStrokedPath(context)
    CGContextClip(context)

    let  startPoint: CGPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect))
    let  endPoint: CGPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect))
    CGContextDrawLinearGradient(context, newBlue, startPoint, endPoint, CGGradientDrawingOptions(rawValue: 0))
}

I only addressed painting the border. I don't know about the text.

Upvotes: 2

Related Questions