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

Drawing rectangles using the CGPoint coordinate system - SWIFT

我可以使用下面的代码绘制一个矩形(有效)。但是,我正在使用 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)

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

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

由于 screen/system 的物理限制,代码无法运行。您需要使用大于 1 的大小(和位置)值才能看到矩形。 Vision 框架也不例外,它只会看到你能看到的,如果那有意义的话。

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)