首页 > 解决方案 > 将 CGFloat 数组标准化为 UIView 帧高度

问题描述

我正在绘制 UIBezierPath 中的 CGFloat 值数组。现在我想规范化这些值,以便数组的最大值将占据整个高度。

至今

let scaleFactor = (waveView.frame.height) * readFile.maxValue

for point in readFile.points {        
    let nextPoint = CGPoint(x: soundPath.currentPoint.x + sampleSpace, y: middleY - (point * scaleFactor) - 1.0)

    soundPath.addLine(to: nextPoint)
    soundPath.move(to: nextPoint)        
}

但它似乎不起作用......

编辑阅读文件:

class ReadFile {
public enum ReadFileError:Error{
    case errorReading(String)

}

/* Player Interval Measured in Miliseconds (By now..) */
var beginPosition:Int32 = 0
var endPosition:Int32 = 0

/* Sample Rate -> Default 48KHz */
var sampleRate:Double = 48000

var samplesSeconds:CGFloat = 5

var maxValue:CGFloat = 0
var points:[CGFloat] = []

}

sampleSpace = 0.2

标签: swiftswift4

解决方案


谢谢安迪的回答,但我终于想通了。

我正在绘制声波,因此它具有正值和负值。

heightMax = waveView.frame.height/2

应用三规则(西班牙语翻译)我最终得到这个:

    func drawSoundWave(windowLength:Int32){

    // Drawing code
    print("\(logClassName): Drawing!!!")
    print("\(logClassName): points COUNT = \(readFile.points.count)")

    let soundPath = UIBezierPath()
    soundPath.lineWidth = lineWidth
    soundPath.move(to: CGPoint(x:0.0 , y: middleY))

    print("\(logClassName) max ")
    for point in readFile.points{

        let normalizedHeight:CGFloat = (waveView.frame.height * point) / (2 * readFile.maxValue)
        let nextPoint = CGPoint(x: soundPath.currentPoint.x + sampleSpace, y: middleY - (normalizedHeight))

        soundPath.addLine(to: nextPoint)
        soundPath.move(to: nextPoint)

    }

    let trackLayer = CAShapeLayer()
    trackLayer.path = soundPath.cgPath

    waveView.layer.addSublayer(trackLayer)

    trackLayer.strokeColor = UIColor.red.cgColor
    trackLayer.lineWidth = lineWidth
    trackLayer.fillColor = UIColor.green.cgColor
    trackLayer.lineCap = kCALineCapRound

}

在哪里

let normalizedHeight:CGFloat = (waveView.frame.height * point) / (2 * readFile.maxValue) 

是给定 readFile.maxValue 和 waveView.frame.height 的归一化值


推荐阅读