如何在Swift 3中在图像上的两点之间画一条线? [英] How to draw a line between two points over an image in swift 3?

查看:173
本文介绍了如何在Swift 3中在图像上的两点之间画一条线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,我想在一张称为mapView的图像的2个点之间画一条线,我尝试使用CGContext,但没有结果,有任何帮助的主意吗?谢谢.

I am new to swift, I want to draw a line between 2 points over an image which I called mapView, I tried to use CGContext but got no result, any idea to help? Thanks.

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()

推荐答案

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

One option is to add a sub view to your image view and add the line drawing code into its draw(_ rect: CGRect) method.

操场实施示例:

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 3中在图像上的两点之间画一条线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆