swift - 如何在 swift 3 中的图像上的两点之间画一条线?

标签 swift cgcontext cgcontextdrawimage

我是 swift 的新手,我想在我称为 mapView 的图像上的 2 点之间画一条线,我尝试使用 CGContext 但没有结果,有什么帮助吗?谢谢。

UIGraphicsBeginImageContext(mapView.bounds.size)
    let context : CGContext = UIGraphicsGetCurrentContext()!
    context.addLines(between: [CGPoint(x:oldX,y:oldY), CGPoint(x:newX, y:newY)])
    context.setStrokeColorSpace(CGColorSpaceCreateDeviceRGB())
    context.setStrokeColor(UIColor.blue.cgColor.components!)
    context.setLineWidth(3)
    mapView?.image?.draw(at: CGPoint(x:0, y:0))
    context.strokePath()
    mapView.image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

最佳答案

一个选项是向您的 ImageView 添加一个 subview ,并将画线代码添加到其draw(_ rect: CGRect) 方法中。

Playground 实现示例:

class LineView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.init(white: 0.0, alpha: 0.0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        if let context = UIGraphicsGetCurrentContext() {
            context.setStrokeColor(UIColor.blue.cgColor)
            context.setLineWidth(3)
            context.beginPath()
            context.move(to: CGPoint(x: 5.0, y: 5.0)) // This would be oldX, oldY
            context.addLine(to: CGPoint(x: 50.0, y: 50.0)) // This would be newX, newY
            context.strokePath()
        }
    }
}


let imageView = UIImageView(image: #imageLiteral(resourceName: "image.png")) // This would be your mapView, here I am just using a random image
let lineView = LineView(frame: imageView.frame)
imageView.addSubview(lineView)

关于swift - 如何在 swift 3 中的图像上的两点之间画一条线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41139767/

相关文章:

IOS Quartz 2D 绘制矩形和调整大小

objective-c - 如何找到一条直线上的点 - Objective c?

ios - 使用 CGContextDrawImage 旋转图像

swift - GMSMapView 上未显示业务 POI,未调用 didTapPOIWithPlaceID

ios - UIView Animate 只有在 IBAction 中时才会动画。我如何让它在我的情况下动画?

ios - 如何画一条完整的线直到结束屏幕

iphone - 核心显卡旋转路径

ios - CGContextDrawImage 在传递 UIImage.CGImage 时颠倒绘制图像

swift - 如何在 .observe 之外使用变量

swift - 以高性能方式获取 CVPixelBuffer(相机帧和 ar 模型)