绿色的 UIImageView 嵌套在 UIView 中。
当我按下开始时,我想画一条线,指示当前正在记录的声级。
我对 Core Graphics 很陌生,并且在 SO 中找到了以下代码,解释了如何在 UYIImageView 上绘图。
func drawLine(from fromPoint: CGPoint, to toPoint: CGPoint) {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)
plotArea.image?.draw(in: view.bounds)
let context = UIGraphicsGetCurrentContext()
context?.move(to: fromPoint)
context?.addLine(to: toPoint)
context?.setLineCap(CGLineCap.round)
context?.setLineWidth(brushWidth)
context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
context?.setBlendMode(CGBlendMode.normal)
context?.strokePath()
plotArea.image = UIGraphicsGetImageFromCurrentImageContext()
plotArea.alpha = opacity
UIGraphicsEndImageContext()
}
调用时,这会在绿色 UIImageView(称为 plotArea)内绘制一条漂亮的线。我想要发生的是线绘制在 UIView(称为 rangeView)的顶部(向用户表明,当线超过绿色图像视图时,他处于正确的水平)谁能指出我重构我的 drawLine 函数在 UIView 而不是 UIImageView 上绘制
当我解决这个问题时,我还需要连续绘制线 - 这意味着当它到达视图的 2/3 时,它应该继续在那个固定的 x 坐标处绘制,并消失在左边(就像一条滚动线)
现在我用这个函数每 0.1 秒调用一次 drawLine 函数:
func animatePin() {
let viewHeight = self.rangeView.frame.height
let ypos = viewHeight/maxDb*CGFloat(self.calculateLevel())
let p = CGPoint(x:self.lastPoint.x+10, y: ypos)
self.drawLine(from: self.lastPoint, to: p)
self.lastPoint = p
}
编辑:通过调用此方法解决了第一部分:
func drawLineFromPoint(start : CGPoint, toPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) {
let path = UIBezierPath()
path.move(to: start)
path.addLine(to: end)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = lineColor.cgColor
shapeLayer.lineWidth = 1.0
view.layer.addSublayer(shapeLayer)
}
EDIT2 - 通过将函数重构为
func drawLineFromPoint(start : CGPoint, toPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) {
let path = UIBezierPath()
path.move(to: start)
path.addLine(to: end)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = lineColor.cgColor
shapeLayer.lineWidth = 1.0
if(end.x > view.frame.width*0.95){
let newRect = CGRect(x: view.frame.origin.x-10, y: view.frame.origin.y, width: view.frame.width+10, height: view.frame.height)
view.frame = newRect
}
if(start != CGPoint.zero){
view.layer.addSublayer(shapeLayer)
}
}