【问题标题】:How to set fillColor and strokColor for path in swift如何在swift中为路径设置fillColor和strokColor
【发布时间】:2019-06-20 19:04:10
【问题描述】:

我正在使用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!
}

【问题讨论】:

  • 您的代码显示您正确设置了笔触颜色和填充颜色。您的实际问题是什么?
  • 我想要边框颜色和填充颜色,但不幸的是我只得到边框颜色。如果我评论我的边框颜色代码,那么我会得到填充颜色。

标签: swift uigraphicscontext mkmapsnapshotter


【解决方案1】:

来自strokePathfillPath 的文档

调用此函数的副作用是清除当前路径。

这意味着调用strokePath后,路径被清除,所以调用fillPath时没有注意绘制

您应该致电context!.drawPath(using: .fillStroke)

【讨论】:

  • 这确实有效,尽管我不得不对线条的绘制进行一些更改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 2019-11-14
  • 2022-12-12
相关资源
最近更新 更多