如何在 Swift 4 中制作虚线或虚线
How to make a dashed or dotted line in Swift 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()
但结果是:
1) [0, 16]
的破折号模式在我看来没有意义。两个值都应大于 0。
2) 除此之外,您的代码是正确的,但是 Xcode 中 UIBezierPath
的 playground 预览忽略了破折号图案(就像它忽略颜色和许多其他设置一样 - 它只是以抽象方式显示路径)。
如果将路径渲染到图像中,虚线图案就会变得可见。这是我使用的代码(我将破折号模式数组更改为 [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
我一直在这样的操场上尝试这样做:
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()
但结果是:
1) [0, 16]
的破折号模式在我看来没有意义。两个值都应大于 0。
2) 除此之外,您的代码是正确的,但是 Xcode 中 UIBezierPath
的 playground 预览忽略了破折号图案(就像它忽略颜色和许多其他设置一样 - 它只是以抽象方式显示路径)。
如果将路径渲染到图像中,虚线图案就会变得可见。这是我使用的代码(我将破折号模式数组更改为 [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