微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我是 swift的新手,我想在我称为mapView的图像上画两条点之间的线,我试图使用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()

解决方法

一种选择是在图像视图中添加子视图,并将线条绘制代码添加到其绘图(_ rect:CGRect)方法中.

示例游乐场实施:

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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐