首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在swift中为path设置fillColor和strokColor

如何在swift中为path设置fillColor和strokColor
EN

Stack Overflow用户
提问于 2019-06-21 03:04:11
回答 1查看 385关注 0票数 0

我正在使用MKMapSnapshotter获取特定区域的图像。

我使用UIGraphicsGetCurrentContext()在图像上绘制线条以显示多边形,

我可以设置线条的颜色,但是我不能设置多边形的填充颜色。

下面是代码

代码语言:javascript
复制
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!
}

我如何才能做到这一点?

解决方案:

代码语言:javascript
复制
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!
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-21 03:18:56

来自strokePathfillPath的文档

作为调用此函数的副作用,当前路径将被清除。

这意味着在调用strokePath之后,路径将被清除,因此在调用fillPath时不需要绘制任何内容

相反,应该调用context!.drawPath(using: .fillStroke)

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56692375

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档