在上一篇(视频播放)中,如果放入的视频不是16:9, 会发现图像的形状会被拉伸,要解决这个问题只需要修改顶点数据就可以了。
上代码
...
let wY = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0)
let hY = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0)
let vs = transformVertices(vertex: vertexs, inputSize: CGSize(width: wY, height: hY), drawableSize: mtkView.drawableSize)
let vertexBuffer = device.makeBuffer(bytes: vs, length: MemoryLayout<Float>.size * 8, options: [])
let textureVerBuffer = device.makeBuffer(bytes: textureCoordinates, length: MemoryLayout<Float>.size * 8, options: [])
renderCommandEncoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0)
renderCommandEncoder.setVertexBuffer(textureVerBuffer, offset: 0, index: 1)
...
/// 顶点转换
func transformVertices(vertex: [Float], inputSize: CGSize, drawableSize: CGSize) -> [Float] {
let inputAspectRatio = inputSize.height / inputSize.width
let drawableAspectRatio = drawableSize.height / drawableSize.width
var xRatio: Float = 1.0
var yRatio: Float = 1.0
if inputAspectRatio > drawableAspectRatio {
yRatio = 1.0
xRatio = Float((inputSize.width / drawableSize.width) * (drawableSize.height / inputSize.height))
}else {
xRatio = 1.0
yRatio = Float((inputSize.height / drawableSize.height) * (drawableSize.width / inputSize.width))
}
let value1 = vertex[0] * xRatio
let value2 = vertex[1] * yRatio
let value3 = vertex[2] * xRatio
let value4 = vertex[3] * yRatio
let value5 = vertex[4] * xRatio
let value6 = vertex[5] * yRatio
let value7 = vertex[6] * xRatio
let value8 = vertex[7] * yRatio
return [value1, value2, value3, value4, value5, value6, value7, value8]
}
经过转换之后,就可以正常的显示图像,如下:
具体实现已经更新到Metal-10(视频播放)中。