How to change UIBezierPath background color?
Asked Answered
H

3

8

I have added these lines of code:

    var radius: CGFloat = UIScreen.mainScreen().bounds.width - 60
    let path: UIBezierPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height), cornerRadius: 0)

    let circlePath: UIBezierPath = UIBezierPath(roundedRect: CGRect(x: 30, y: (UIScreen.mainScreen().bounds.height - radius) / 2 - (navigationController?.navigationBar.frame.height)!, width: radius, height: radius), cornerRadius: radius)

    path.appendPath(circlePath)

but it gives me this result

enter image description here

How can I make my circle background color - clearColor() ?

I tried this one:

UIColor.whiteColor().setFill()
circlePath.fill()

But it did not make any sense

Hards answered 22/1, 2016 at 8:13 Comment(2)
Why does it not make any sense ?Rosalie
@Rosalie that's that I want to know :)Hards
Z
16

Try this:

let radius: CGFloat = 50
let path: UIBezierPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 50, height: 50), cornerRadius: 0)

let circlePath: UIBezierPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: radius, height: radius), cornerRadius: radius)

path.append(circlePath)

let fillLayer = CAShapeLayer()
fillLayer.path = path.cgPath
fillLayer.fillColor = UIColor.red.cgColor
yourView.layer.addSublayer(fillLayer)

Paths do not have color; layers have color.

You need to create a layer based on a path, and add it to the layer of your view as shown in the code above.

Zohar answered 22/1, 2016 at 8:30 Comment(1)
@Marin Enjoy swifty coding.!Zohar
C
1

try this:

let context = UIGraphicsGetCurrentContext();

CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor);
Cockeye answered 22/1, 2016 at 8:24 Comment(3)
Call circlePath.fill() at lastCockeye
While this may answer the question, it would be best if you could provide a little explanation for why it does so.Marybellemarybeth
You are right. Thank you for your advice. My English is not very good, but I'll try.Cockeye
F
0

Be mindful that CAShapeLayer has a property called fillColor which by default is black.

If you want it to be clear just make it nil.

    let layer = CAShapeLayer()

    let linePath = UIBezierPath()
    linePath.move(to: .init(x: .zero, y: bounds.height))
    linePath.addLine(to: .init(x: bounds.width, y: bounds.height))
    linePath.addLine(to: .init(x: bounds.width, y: .zero))

    layer.path = linePath.cgPath
    layer.strokeColor = UIColor.grey.cgColor
    layer.fillColor = nil // here
    layer.lineWidth = 1

enter image description here

Foxe answered 16/3, 2023 at 22:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.