我如何在 UIView 中使用这个圆形绘图代码?

How do I use this circle drawing code in a UIView?

我正在为客户制作一个应用程序,其中包含一些呼吸技巧。他想要的是中间有一个圆圈。因为吸气变大,因为呼气变细。问题是,他希望中间有一个很酷的动画圆圈,而不仅仅是一个标准的圆圈。我给他看了这张来自 YouTube 的照片:

视频中使用的代码如下所示:

func drawRotatedSquares() {
    UIGraphicsBeginImageContextWithOptions(CGSize(width: 512, height: 512), false, 0)
    let context = UIGraphicsGetCurrentContext()

    context!.translateBy(x: 256, y: 256)
    let rotations = 16
    let amount = M_PI_2 / Double(rotations)

    for i in 0 ..< rotations {
        context!.rotate(by: CGFloat(amount))
        //context!.addRect(context, CGRect(x: -128, y: -128, width: 256, height: 256))
        context!.addRect(CGRect(x: -128, y: -128, width: 256, height: 256))
    }

    context!.setStrokeColor(UIColor.black as! CGColor)

    let img = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    imageView.image = img
}

但是如果我 运行 它,我的模拟器只显示一个白屏。如何将这个圆圈放入我的 Swift 3 应用程序中,代码会是什么样子?是否可以不在 ImageView 中显示,而只是在视图中显示?

非常感谢!

您发布了一个生成 UIImage 并将其安装在图像视图中的单一方法。如果屏幕上没有图像视图,则它不会显示。

如果您在视图控制器中创建图像视图并将插座连接到图像视图,则上述代码应将图像视图安装到图像中并将其绘制在屏幕上。

您可以将您发布的代码重写为 UIView 的自定义子类的 draw(_:) 方法,在这种情况下,您将摆脱上下文设置和 UIImage 内容,而只需在当前上下文中绘制.我建议您搜索 UIView 自定义 draw(_:) 方法以获得更多指导。

这是一个 UIView subclass.

的实现

要设置:

  1. 将此 class 添加到您的 Swift 项目中。
  2. 将 UIView 添加到您的故事板并将 class 更改为 Circle
  3. 为您的 viewController

    添加一个插座
    @IBOutlet var circle: Circle!
    
  4. 更改乘数的值以更改圆的大小。

    circle.multiplier = 0.5  // 50% of size of view
    

class Circle: UIView {
    var multiplier: CGFloat = 1.0 {
        didSet {
            setNeedsDisplay()
        }
    }

    override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()!

        // Calculate size of square edge that fits into the view   
        let size = min(bounds.width, bounds.height) * multiplier / CGFloat(sqrt(2)) / 2

        // Move origin to center of the view            
        context.translateBy(x: center.x, y: center.y)

        // Create a path to draw a square    
        let path = UIBezierPath()
        path.move(to: CGPoint(x: -size, y: -size))
        path.addLine(to: CGPoint(x: -size, y: size))
        path.addLine(to: CGPoint(x: size, y: size))
        path.addLine(to: CGPoint(x: size, y: -size))
        path.close()

        UIColor.black.setStroke()

        let rotations = 16
        let amount = .pi / 2 / Double(rotations)

        for _ in 0 ..< rotations {
            // Rotate the context
            context.rotate(by: CGFloat(amount))

            // Draw a square
            path.stroke()
        }
    }
}

这里是 运行 游乐场: