核心代码:
import UIKit
import GLKit
extension Array {
func s_size() -> Int {
return self.count * MemoryLayout<Point>.size(ofValue: self[0] as! Point)
}
}
struct Point {
var x: Float
var y: Float
var z: Float
}
var vertix = [
Point(x: 0.5, y: -0.5, z: 0),
Point(x: 0.5, y: 0.5, z: 0),
Point(x: -0.5, y: 0.5, z: 0),
Point(x: -0.5, y: -0.5, z: 0)
]
class RectangleViewController: GLKViewController {
var vertexBuffer: GLuint = 0
var baseEffect = GLKBaseEffect()
override func viewDidLoad() {
super.viewDidLoad()
// 1
let view = self.view as! GLKView
view.context = EAGLContext(api: EAGLRenderingAPI.openGLES3)!
EAGLContext.setCurrent(view.context)
// 2
baseEffect.constantColor = GLKVector4Make(1, 0, 0, 0)
baseEffect.useConstantColor = GLboolean(GL_TRUE)
// 3
glGenBuffers(1, &vertexBuffer)
glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexBuffer)
glBufferData(GLenum(GL_ARRAY_BUFFER), vertix.s_size(), vertix, GLenum(GL_STATIC_DRAW))
}
override func glkView(_ view: GLKView, drawIn rect: CGRect) {
baseEffect.prepareToDraw()
glClear(GLenum(GL_COLOR_BUFFER_BIT))
glVertexAttribPointer(0, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<Point>.size), nil)
glEnableVertexAttribArray(0)
glDrawArrays(GLenum(GL_TRIANGLE_FAN), 0, GLsizei(vertix.count))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}