加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:39:29 所属栏目:百科 来源:网络整理
导读:我是 swift的新手,我想在我称为mapView的图像上画两条点之间的线,我试图使用CGContext但没有结果,任何想法都有帮助吗?谢谢. UIGraphicsBeginImageContext(mapView.bounds.size) let context : CGContext = UIGraphicsGetCurrentContext()! context.addLines
我是 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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读