如何计算圆形矩阵的正确位置以适应具有比例间隙的给定视图?

时间:2016-12-07 20:59:10

标签: ios swift

我对iOS开发很新,我试图在UIView中显示一个10x10网格,尊重它的边界,我希望根据设备的可用宽度/高度来计算圆圈。

到目前为止我没有运气的尝试:

func setUpPoints() {
    let matrixSize = 10
    let diameter = (min(painelView.frame.size.width, painelView.frame.size.height) / CGFloat(matrixSize + 1)).rounded(.down)
    let radius = diameter / 2

    for i in 0...matrixSize {

        for j in 0...matrixSize {
            let x = CGFloat(i) * diameter + radius
            let y = CGFloat(j) * diameter + radius
            let frame = CGRect(x: x, y: y, width: diameter, height: diameter)
            let circle = Circle(frame: frame)
            circle.tag = j * matrixSize + i + 1
            painelView.addSubview(circle)

        }
    }

}

我的目标是按比例分配灰色矩形内的圆圈,使其看起来像Android模式锁定屏幕:

enter image description here

有人可以给我一些指示吗?

感谢。

1 个答案:

答案 0 :(得分:1)

如果我理解你想要做什么,那么下面一行:

let radius = (painelView.frame.size.width + painelView.frame.size.height) / CGFloat(matrixSize * 2)

应该是:

let radius = (min(painelView.frame.size.width, painelView.frame.size.height) / CGFloat(matrixSize + 1)).rounded(.down)

上述更改将允许" square"圆圈适合较小的视图 - 视图的宽度或高度,允许在"方形"周围的间隙。等于每个圆的直径的一半。

您还需要将两个循环更改为以0开头。

for i in 0..<matrixSize {
    for j in 0..<matrixSize {

BTW - 您的radius变量确实是diameter。而gap实际上是radius

以下代码提供了圆形正方形周围的边框,并且它包含圆圈之间的一些空格。根据需要进行调整。

func setUpPoints() {
    let matrixSize = 10
    let borderRatio = CGFloat(0.5) // half a circle diameter - change as desired
    let gapRatio = CGFloat(0.25) // quarter circle diameter - change as desired
    let squareSize = min(painelView.frame.size.width, painelView.frame.size.height)
    let diameter = (squareSize / (CGFloat(matrixSize) + 2 * borderRatio + CGFloat(matrixSize - 1) * gapRatio)).rounded(.down)
    let centerToCenter = (diameter + diameter * gapRatio).rounded(.down)
    let borderSize = (diameter * borderRatio).rounded()

    for i in 0..<matrixSize {
        for j in 0..<matrixSize {
            let x = CGFloat(i) * centerToCenter + borderSize
            let y = CGFloat(j) * centerToCenter + borderSize
            let frame = CGRect(x: x, y: y, width: diameter, height: diameter)
            let circle = Circle(frame: frame)
            circle.tag = j * matrixSize + i + 1
            painelView.addSubview(circle)
        }
    }
}