Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the color of a UIBezierPath in Swift?

I have an instance of UIBezierPath and I want to change the color of the stroke to something other than black. Does anyone know how to do this in Swift?

like image 302
bhzag Avatar asked Aug 27 '14 17:08

bhzag


Video Answer


2 Answers

With Swift 5, UIColor has a setStroke() method. setStroke() has the following declaration:

func setStroke()

Sets the color of subsequent stroke operations to the color that the receiver represents.

Therefore, you can use setStroke() like this:

strokeColor.setStroke() // where strokeColor is a `UIColor` instance

The Playground code below shows how to use setStroke() alongside UIBezierPath in order to draw a circle with a green fill color and a light grey stroke color inside a UIView subclass:

import UIKit
import PlaygroundSupport

class MyView: UIView {

    override func draw(_ rect: CGRect) {
        // UIBezierPath
        let newRect = CGRect(
            x: bounds.minX + ((bounds.width - 79) * 0.5 + 0.5).rounded(.down),
            y: bounds.minY + ((bounds.height - 79) * 0.5 + 0.5).rounded(.down),
            width: 79,
            height: 79
        )
        let ovalPath = UIBezierPath(ovalIn: newRect)

        // Fill
        UIColor.green.setFill()
        ovalPath.fill()

        // Stroke
        UIColor.lightGray.setStroke()
        ovalPath.lineWidth = 5
        ovalPath.stroke()
    }

}

let myView = MyView(frame: CGRect(x: 0, y: 0, width: 200, height: 300))
PlaygroundPage.current.liveView = myView
like image 116
Imanou Petit Avatar answered Sep 23 '22 05:09

Imanou Petit


Let's assume you want to use the color red instead to stroke a rounded rectangle; This is how you do it in Swift 3 :

    // Drawing the border of the rounded rectangle:
    let redColor = UIColor.red
    redColor.setStroke() // Stroke subsequent views with a red color
    let roundedRectagle = CGRect(x: 0,y: 0, width: 90,height: 20)
    let rectangleBorderPath = UIBezierPath(roundedRect: roundedRectangle,cornerRadius: 5)
    roundedRectangle.borderWidth = 1
    roundedRectangle.stroke() // Apply the red color stroke on this view

The second and last lines of the above code are important in answering your question.I hope this answer is helpful.

like image 29
Lehlohonolo_Isaac Avatar answered Sep 23 '22 05:09

Lehlohonolo_Isaac