2017-10-13 62 views
0

我一直在努力做到這一點在這樣的遊樂場:如何使一個虛線或虛線斯威夫特4

import UIKit 
import XCPlayground 

let path = UIBezierPath() 
path.move(to: CGPoint(x:10,y:10)) 
path.addLine(to: CGPoint(x:290,y:10)) 
path.lineWidth = 2 

let dashPattern : [CGFloat] = [0, 16] 
path.setLineDash(dashPattern, count: 2, phase: 0) 
path.lineCapStyle = CGLineCap.round 
path.lineCapStyle = .butt 
UIGraphicsBeginImageContextWithOptions(CGSize(width:300, height:20), false, 2) 
path.stroke() 

XCPlaygroundPage.currentPage.captureValue(value: UIGraphicsGetImageFromCurrentImageContext(), withIdentifier: "image") 
UIGraphicsEndImageContext() 

但結果是:

enter image description here

回答

2

1 )[0, 16]的破折號模式在我看來沒有意義。這兩個值應該大於0.

2)除此之外,您的代碼是正確的,但Xcode中UIBezierPath的遊樂場預覽忽略了破折號模式(就像忽略顏色和許多其他設置一樣 - 它只是顯示路徑以抽象的方式)。

如果將路徑渲染到圖像中,則虛線圖案變得可見。這裏是我使用的代碼(我將短劃線陣列數組更改爲[16,16]):

import UIKit 
import XCPlayground 

let path = UIBezierPath() 
path.move(to: CGPoint(x:10,y:10)) 
path.addLine(to: CGPoint(x:290,y:10)) 
path.lineWidth = 2 

let dashPattern : [CGFloat] = [16, 16] 
path.setLineDash(dashPattern, count: 2, phase: 0) 
path.lineCapStyle = CGLineCap.round 
path.lineCapStyle = .butt 

let renderer = UIGraphicsImageRenderer(size: CGSize(width: 300, height: 20)) 
let image = renderer.image { context in 
    path.stroke() 
} 
// image now contains an image of the path 
+0

謝謝!這就是訣竅:) – Menno

+0

@Ola Begemann我們如何爲iOS 9做到這一點? –