2014-08-27 14 views
11

Ho un'istanza di UIBezierPath e voglio cambiare il colore del tratto in qualcosa di diverso dal nero. Qualcuno sa come farlo in Swift?Come cambiare il colore di un UIBezierPath in Swift?

+6

La risposta di POB è utile qui, ma è importante capire che un percorso di Bézier non ha colore. È una descrizione di una curva. Solo le penne hanno il colore e la risposta del POB si basa sull'impostazione del colore della penna. –

risposta

27

Con Swift 3, UIColor ha un metodo setStroke(). setStroke() ha la seguente dichiarazione:

func setStroke() 

Imposta il colore delle operazioni ictus successivi al colore che il ricevitore rappresenta.

Pertanto, è possibile utilizzare setStroke() come questo:

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

Il codice parco giochi sotto mostra come utilizzare setStroke() fianco UIBezierPath al fine di disegnare un cerchio con un colore di riempimento verde e una luce colore tratto grigio all'interno di una sottoclasse UIView:

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 
1

Supponiamo che tu voglia usare il colore rosso invece per accarezzare un rettangolo arrotondato; Questo è come si fa a 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 

La seconda e ultime righe del codice di cui sopra sono importanti a rispondere alle sue question.I sperano questa risposta è utile.

Problemi correlati