Julian Pomper Julian Pomper - 1 year ago 65
Swift Question

Why can't I fill a UIBezierPath with custom UIColor?

I want to fill a

with my custom color, but only the default colors like
are working.

Here is my code:

override func drawRect(rect: CGRect) {

let layerHeight = self.layer.frame.height
let layerWidth = self.layer.frame.width
let width:CGFloat = 50

let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(layerWidth, layerHeight))
bezierPath.addLineToPoint(CGPointMake(layerWidth, layerHeight - width))
bezierPath.addLineToPoint(CGPointMake(layerWidth - width, layerHeight))

// UIColor.blueColor().setFill() works, but a custom color does not:
UIColor(colorLiteralRed: 23, green: 34, blue: 200, alpha: 1).setFill()

Answer Source

You are using wrong values. The color values have to be in range 0.0 - 1.0:

UIColor(colorLiteralRed: 0.2, green: 0.3, blue: 0.9, alpha: 1)

I would then recommend to use a slightly different initializer instead:

UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0)

What happened previously in your code is that all values above 1.0 are treated as 1.0, therefore together forming white, which you probably did not see as filling anything.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download