使用CGPoint坐标系绘制矩形 - SWIFT

时间:2018-05-15 07:51:31

标签: ios swift core-graphics cgpoint apple-vision

我可以使用下面的代码(工作)绘制一个矩形。但是,我使用Vison框架来检测矩形,但它给我的CGPoint值小于1.0。当我输入这些坐标绘制一个矩形时,我什么也得不回来。请问一些建议吗?

工作 - 我得到一个矩形

    let rectangle = UIBezierPath.init()

    rectangle.move(to: CGPoint.init(x: 100, y: 100))
    rectangle.addLine(to: CGPoint.init(x: 200, y: 130))
    rectangle.addLine(to: CGPoint.init(x: 300, y: 400))
    rectangle.addLine(to: CGPoint.init(x: 100, y: 500))

    rectangle.close()

    let rec = CAShapeLayer.init()
    rec.path = rectangle.cgPath
    rec.fillColor = UIColor.red.cgColor
    self.view.layer.addSublayer(rec)

不起作用(没有矩形):

    let rectangle = UIBezierPath.init()

    rectangle.move(to: CGPoint.init(x: 0.154599294066429, y: 0.904223263263702))

    rectangle.addLine(to: CGPoint.init(x: 0.8810795545578, y: 0.970198452472687))
    rectangle.addLine(to: CGPoint.init(x: 0.16680309176445, y: 0.0157230049371719))
    rectangle.addLine(to: CGPoint.init(x: 0.878569722175598, y: 0.128135353326797))

    rectangle.close()

    let rec = CAShapeLayer.init()
    rec.path = rectangle.cgPath
    rec.fillColor = UIColor.red.cgColor
    self.view.layer.addSublayer(rec)

2 个答案:

答案 0 :(得分:1)

让我们分析一下你的到来是什么。在第一个例子中,您正在绘制一个大小约为200px×400px的矩形,当然,这将完全按照您的预期显示。

在第二个例子中,你正在绘制一个大约0.7px乘0.8px的矩形,ish。现在从逻辑上考虑一下,屏幕应该如何代表0.7像素?它不能!像素是您可以拥有的最小代表,即单色方块。

由于屏幕/系统的物理限制,代码无法正常工作。您需要使用大于1的大小(和位置)值来查看矩形。 Vision框架没有什么不同,它只会看到你能看到的东西,如果这是有道理的。

答案 1 :(得分:1)

Vision框架返回的点是由视口完整大小的百分比表示的坐标。如果您的视口是640 x 480(例如),那么您的第一个点是CGPoint(x: 0.154599294066429 * 640, y: 0.904223263263702 * 480)。考虑到这一点,将您的代码更改为类似的内容,应该没问题:

let rectangle = UIBezierPath.init()
let width = // your width - Maybe UIScreen.main.bounds.size.width ?
let height = // your height - Maybe UIScreen.main.bounds.size.height ?

rectangle.move(to: CGPoint.init(x: width  * 0.154599294066429, y: height * 0.904223263263702))

rectangle.addLine(to: CGPoint.init(x: width * 0.8810795545578, y: height * 0.970198452472687))
rectangle.addLine(to: CGPoint.init(x: width * 0.16680309176445, y: height * 0.0157230049371719))
rectangle.addLine(to: CGPoint.init(x: width * 0.878569722175598, y: height * 0.128135353326797))

rectangle.close()

let rec = CAShapeLayer.init()
rec.path = rectangle.cgPath
rec.fillColor = UIColor.red.cgColor
self.view.layer.addSublayer(rec)
相关问题