我目前有这个代码,它允许我使用Image Graphics Context创建一个呼吸描记器:
func generateSpirograph(insideRadius: Double = 0.5, rotationalSpeed: Double = -31/3, color: UIColor = .blue) {
//Creates an 800*800 image that is transparent
guard let transparentImage = UIImage(named: "transparent.png") else { return }
let imgCenter = CGPoint(x: transparentImage.size.width/2, y: transparentImage.size.height/2)
var multiplier: Double!
if insideRadius <= 1 {
multiplier = (2 - insideRadius)*100
} else {
multiplier = 150/insideRadius
}
//The size of the new bitmap
UIGraphicsBeginImageContext(transparentImage.size)
transparentImage.draw(at: .zero)
//Setup Context
guard let context = UIGraphicsGetCurrentContext() else { return }
context.move(to: CGPoint(x: multiplier*(1+insideRadius)+Double(imgCenter.x), y: Double(imgCenter.y)))
for t in 0 ... 2000 {
let radians = Double(t) * Double.pi / 180
let x = (cos(radians)+insideRadius*cos(rotationalSpeed*radians))
let y = (sin(radians)+insideRadius*sin(rotationalSpeed*radians))
// let x = (outsideRadius+insideRadius)*sin(location*radians)+penLocation*insideRadius*sin(rotationalSpeed*location*radians)
// let y = (outsideRadius+insideRadius)*cos(location*radians)+penLocation*insideRadius*cos(rotationalSpeed*location*radians)
context.addLine(to: CGPoint(x: multiplier*x+Double(imgCenter.x), y: multiplier*y+Double(imgCenter.y)))
}
context.setLineWidth(1)
context.setStrokeColor(color.cgColor)
context.drawPath(using: .stroke)
guard let spirographImg = UIGraphicsGetImageFromCurrentImageContext() else { return }
UIGraphicsEndImageContext()
let spirographImageView = UIImageView(image: spirographImg)
spirographImageView.contentMode = .scaleAspectFit
spirographImageView.translatesAutoresizingMaskIntoConstraints = false
spirographImageView.frame = CGRect(x: 0, y: 0, width: view.frame.width/2, height: view.frame.width/2)
view.addSubview(spirographImageView)
}
它会立即运行,然后一次性绘制肺活量图。我想要发生的是它的动画,所以你可以看到正在形成的线。我怎么能这样做?
谢谢!