[英]How to set fillColor and strokColor for path in swift
我正在使用MKMapSnapshotter
獲取特定區域的圖像。
我使用UIGraphicsGetCurrentContext()
在圖像上繪制線條以顯示多邊形,
我可以設置線條顏色,但是無法為多邊形設置填充顏色。
下面是代碼
private func drawLineOnImage(snapshot: MKMapSnapshotter.Snapshot, coordinates: [CLLocationCoordinate2D]) -> UIImage {
let image = snapshot.image
UIGraphicsBeginImageContextWithOptions(getMapFrameSize(), true, 0)
image.draw(at: CGPoint.zero)
let context = UIGraphicsGetCurrentContext()
context!.setLineWidth(2.0)
context!.setStrokeColor(UIColor.red.cgColor)
context!.move(to: snapshot.point(for: coordinates[0]))
for i in 0...coordinates.count-1 {
context!.addLine(to: snapshot.point(for: coordinates[i]))
context!.move(to: snapshot.point(for: coordinates[i]))
}
context!.strokePath()
context!.setFillColor(UIColor.green.cgColor)
context!.fillPath()
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultImage!
}
我該如何實現?
解:
private func drawLineOnImage(snapshot: MKMapSnapshotter.Snapshot, coordinates: [CLLocationCoordinate2D]) -> UIImage {
let image = snapshot.image
UIGraphicsBeginImageContextWithOptions(getMapFrameSize(), true, 0)
image.draw(at: CGPoint.zero)
let context = UIGraphicsGetCurrentContext()!
context.setLineWidth(2.0)
context.setStrokeColor(annotationColor.cgColor)
context.setFillColor(annotationColor.withAlphaComponent(0.5).cgColor)
var coordinates = coordinates
if let firstPoint = coordinates.first { context.move(to: snapshot.point(for: firstPoint)) }
context.move(to: snapshot.point(for: coordinates[0]))
coordinates.removeFirst()
coordinates.forEach { context.addLine(to: snapshot.point(for: $0)) }
context.drawPath(using: .fillStroke)
context.fillPath()
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resultImage!
}
從文檔獲取strokePath
和fillPath
作為調用此函數的副作用,清除了當前路徑。
這意味着在調用strokePath
,該路徑將被清除,因此在您調用fillPath
時fillPath
繪制
相反,您應該調用context!.drawPath(using: .fillStroke)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.