二十二 案例:旋轉的立方體(GLKit+CoreAnimation)

GLKit實現

效果圖

image

流程

image

具體步驟

1.準備工作

  • 定義頂點坐標,紋理坐標,法線數據結構體
typedef struct {
    GLKVector3 positionCoord;   //頂點坐標
    GLKVector2 textureCoord;    //紋理坐標
    GLKVector3 normal;          //法線
} CCVertex;
  • 定義正方體的三角形組成的頂點個數
// 頂點數:每個面有兩個三角形組成,兩三角形6個頂點,共6個面,立方體頂點個數是6*6= 36
static NSInteger const kCoordCount = 36;
  • 實現GLKViewDelegate
@interface CubeViewController () <GLKViewDelegate>
@end

  • 定義GLKView對象glkView
//定義GLKView對象
@property (nonatomic, strong) GLKView *glkView;
  • 定義GLKBaseEffect對象 baseEffect;
//定義GLKBaseEffect對象
@property (nonatomic, strong) GLKBaseEffect *baseEffect;
  • 定義數據結構體數組 vertices
//定義數據結構體數組
@property (nonatomic, assign) CCVertex *vertices;
  • 定義定時器對象 displayLink;
//定義定時器對象
@property (nonatomic, strong) CADisplayLink *displayLink;
  • 記錄旋轉角度變量 angle
//記錄旋轉角度變量
@property (nonatomic, assign) NSInteger angle;
  • 頂點緩沖區ID vertexBuffer
//頂點緩沖區ID
@property (nonatomic, assign) GLuint vertexBuffer;

OpenGL ES相關初始化 commonInit函數

  • 1.設置View背景色
self.view.backgroundColor = [UIColor blackColor];
  • 2.初始化上下文,設置當前上下文
//創建context
     EAGLContext *context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    //設置當前context
    [EAGLContext setCurrentContext:context];
  • 3.創建GLKView并設置代理
CGRect frame = CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.width);
    self.glkView = [[GLKView alloc] initWithFrame:frame context:context];
    self.glkView.backgroundColor = [UIColor clearColor];
    self.glkView.delegate = self;
  • 4.使用深度緩存
self.glkView.drawableDepthFormat = GLKViewDrawableDepthFormat24;
    //默認是(0, 1),這里用于翻轉 z 軸,使正方形朝屏幕外
    glDepthRangef(1, 0); 

    1. 配置視圖創建的渲染緩存區
self.glkView.drawableColorFormat = GLKViewDrawableColorFormatRGBA8888;
    self.glkView.drawableStencilFormat = GLKViewDrawableStencilFormat8;
    self.glkView.drawableMultisample = GLKViewDrawableMultisample4X;
  • 6.將GLKView 添加self.view 上
[self.view addSubview:self.glkView];
  • 7.加載紋理數據 setUpTexture函數
  1. 獲取紋理圖片路徑
NSString *imagePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"meimei.jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
  1. 設置紋理參數
NSDictionary *options = @{GLKTextureLoaderOriginBottomLeft : @(YES)};
    GLKTextureInfo *textureInfo = [GLKTextureLoader textureWithCGImage:[image CGImage] options:options error:NULL];
  1. 使用蘋果GLKit提供GLKBaseEffect完成著色器工作
self.baseEffect = [[GLKBaseEffect alloc] init];
    self.baseEffect.texture2d0.name = textureInfo.name;
    self.baseEffect.texture2d0.target = textureInfo.target;
    //開啟光照效果
    self.baseEffect.light0.enabled = YES;
    //漫反射顏色
    self.baseEffect.light0.diffuseColor = GLKVector4Make(1, 1, 1, 1);
    //光源位置
    self.baseEffect.light0.position = GLKVector4Make(-0.5, -0.5, 5, 1);
  • 8.加載圖片頂點坐標和紋理坐標 setUpVertexData函數
  1. 設置頂點數組(頂點坐標,紋理坐標)
//開辟頂點數據空間(數據結構SenceVertex 大小 * 頂點個數kCoordCount)
    self.vertices = malloc(sizeof(CCVertex) * kCoordCount);
    
    // 前面
    self.vertices[0] = (CCVertex){{-0.5, 0.5, 0.5}, {0, 1}, {0, 0, 1}};
    self.vertices[1] = (CCVertex){{-0.5, -0.5, 0.5}, {0, 0}, {0, 0, 1}};
    self.vertices[2] = (CCVertex){{0.5, 0.5, 0.5}, {1, 1}, {0, 0, 1}};
    self.vertices[3] = (CCVertex){{-0.5, -0.5, 0.5}, {0, 0}, {0, 0, 1}};
    self.vertices[4] = (CCVertex){{0.5, 0.5, 0.5}, {1, 1}, {0, 0, 1}};
    self.vertices[5] = (CCVertex){{0.5, -0.5, 0.5}, {1, 0}, {0, 0, 1}};
    
    // 上面
    self.vertices[6] = (CCVertex){{0.5, 0.5, 0.5}, {1, 1}, {0, 1, 0}};
    self.vertices[7] = (CCVertex){{-0.5, 0.5, 0.5}, {0, 1}, {0, 1, 0}};
    self.vertices[8] = (CCVertex){{0.5, 0.5, -0.5}, {1, 0}, {0, 1, 0}};
    self.vertices[9] = (CCVertex){{-0.5, 0.5, 0.5}, {0, 1}, {0, 1, 0}};
    self.vertices[10] = (CCVertex){{0.5, 0.5, -0.5}, {1, 0}, {0, 1, 0}};
    self.vertices[11] = (CCVertex){{-0.5, 0.5, -0.5}, {0, 0}, {0, 1, 0}};
    
    // 下面
    self.vertices[12] = (CCVertex){{0.5, -0.5, 0.5}, {1, 1}, {0, -1, 0}};
    self.vertices[13] = (CCVertex){{-0.5, -0.5, 0.5}, {0, 1}, {0, -1, 0}};
    self.vertices[14] = (CCVertex){{0.5, -0.5, -0.5}, {1, 0}, {0, -1, 0}};
    self.vertices[15] = (CCVertex){{-0.5, -0.5, 0.5}, {0, 1}, {0, -1, 0}};
    self.vertices[16] = (CCVertex){{0.5, -0.5, -0.5}, {1, 0}, {0, -1, 0}};
    self.vertices[17] = (CCVertex){{-0.5, -0.5, -0.5}, {0, 0}, {0, -1, 0}};
    
    // 左面
    self.vertices[18] = (CCVertex){{-0.5, 0.5, 0.5}, {1, 1}, {-1, 0, 0}};
    self.vertices[19] = (CCVertex){{-0.5, -0.5, 0.5}, {0, 1}, {-1, 0, 0}};
    self.vertices[20] = (CCVertex){{-0.5, 0.5, -0.5}, {1, 0}, {-1, 0, 0}};
    self.vertices[21] = (CCVertex){{-0.5, -0.5, 0.5}, {0, 1}, {-1, 0, 0}};
    self.vertices[22] = (CCVertex){{-0.5, 0.5, -0.5}, {1, 0}, {-1, 0, 0}};
    self.vertices[23] = (CCVertex){{-0.5, -0.5, -0.5}, {0, 0}, {-1, 0, 0}};
    
    // 右面
    self.vertices[24] = (CCVertex){{0.5, 0.5, 0.5}, {1, 1}, {1, 0, 0}};
    self.vertices[25] = (CCVertex){{0.5, -0.5, 0.5}, {0, 1}, {1, 0, 0}};
    self.vertices[26] = (CCVertex){{0.5, 0.5, -0.5}, {1, 0}, {1, 0, 0}};
    self.vertices[27] = (CCVertex){{0.5, -0.5, 0.5}, {0, 1}, {1, 0, 0}};
    self.vertices[28] = (CCVertex){{0.5, 0.5, -0.5}, {1, 0}, {1, 0, 0}};
    self.vertices[29] = (CCVertex){{0.5, -0.5, -0.5}, {0, 0}, {1, 0, 0}};
    
    // 后面
    self.vertices[30] = (CCVertex){{-0.5, 0.5, -0.5}, {0, 1}, {0, 0, -1}};
    self.vertices[31] = (CCVertex){{-0.5, -0.5, -0.5}, {0, 0}, {0, 0, -1}};
    self.vertices[32] = (CCVertex){{0.5, 0.5, -0.5}, {1, 1}, {0, 0, -1}};
    self.vertices[33] = (CCVertex){{-0.5, -0.5, -0.5}, {0, 0}, {0, 0, -1}};
    self.vertices[34] = (CCVertex){{0.5, 0.5, -0.5}, {1, 1}, {0, 0, -1}};
    self.vertices[35] = (CCVertex){{0.5, -0.5, -0.5}, {1, 0}, {0, 0, -1}};
  1. 開辟頂點緩存區
  • 創建頂點緩存區標識符ID
glGenBuffers(1, &_vertexBuffer);
  • 綁定頂點緩存區
glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
  • 將頂點數組的數據copy到頂點緩存區中
GLsizeiptr bufferSizeBytes = sizeof(CCVertex) * kCoordCount;
glBufferData(GL_ARRAY_BUFFER, bufferSizeBytes, self.vertices, GL_STATIC_DRAW);
  1. 打開讀取通道
  • 頂點坐標數據 GLKVertexAttribPosition
glEnableVertexAttribArray(GLKVertexAttribPosition);glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(CCVertex), NULL + offsetof(CCVertex, positionCoord));
  • 紋理坐標數據 GLKVertexAttribTexCoord0
glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(CCVertex), NULL + offsetof(CCVertex, textureCoord));
  • 法線數據 GLKVertexAttribNormal
glEnableVertexAttribArray(GLKVertexAttribNormal);
glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, sizeof(CCVertex), NULL + offsetof(CCVertex, normal));

添加CADisplayLink定時器 addCADisplayLink

  • 初始化定時器,并設置回調
        //CADisplayLink 類似定時器,提供一個周期性調用.屬于QuartzCore.framework中.
    //具體可以參考該博客 https://www.cnblogs.com/panyangjun/p/4421904.html
    self.angle = 0;
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateAngle)];
    [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
  • 定時器回調,設置旋轉后提交重新渲染
//計算旋轉度數
self.angle = (self.angle + 5) % 360;

//修改baseEffect.transform.modelviewMatrix
self.baseEffect.transform.modelviewMatrix = GLKMatrix4MakeRotation(GLKMathDegreesToRadians(self.angle), 0.3, 1, 0.7);

//重新渲染
[self.glkView display];

釋放資源 dealloc

  • 當前上下文置為nil
if ([EAGLContext currentContext] == self.glkView.context) {
        [EAGLContext setCurrentContext:nil];
    }
  • 釋放數據結構
if (_vertices) {
        free(_vertices);
        _vertices = nil;
    }
  • 刪除頂點緩存區
if (_vertexBuffer) {
        glDeleteBuffers(1, &_vertexBuffer);
        _vertexBuffer = 0;
    }
  • displayLink 失效
[self.displayLink invalidate];

GLKit實現旋轉的立方體完整代碼參考:github

CoreAnimation實現

效果圖

image

流程

image

具體步驟

準備工作

  • IBOutlet容器View
@property (weak, nonatomic) IBOutlet UIView *containerView;
  • IBOutlet 6個面
@property (strong, nonatomic) IBOutlet UIView *view0;
@property (strong, nonatomic) IBOutlet UIView *view1;
@property (strong, nonatomic) IBOutlet UIView *view2;
@property (strong, nonatomic) IBOutlet UIView *view3;
@property (strong, nonatomic) IBOutlet UIView *view4;
@property (strong, nonatomic) IBOutlet UIView *view5;
  • 6個面的數組數組faces
@property(nonatomic,strong)NSArray *faces;
  • 定時器對象
@property (nonatomic, strong) CADisplayLink *displayLink;
  • 記錄旋轉角度
@property (nonatomic, assign) NSInteger angle;

viewDidLoad

  • 添加立方體的6個面
self.faces = @[_view0,_view1,_view2,_view3,_view4,_view5];
  • 將容器View先后繞X旋轉45度,繞Y軸旋轉45度
/父View的layer圖層
    CATransform3D perspective = CATransform3DIdentity;
    //m34影響到透視關系 參考 http://www.lxweimin.com/p/3dd14cfbdc53
    perspective.m34 = -1.0 / 500.0;
    perspective = CATransform3DRotate(perspective, -M_PI_4, 1, 0, 0);
    perspective = CATransform3DRotate(perspective, -M_PI_4, 0, 1, 0);
        //特別注意:旋轉時,我們需要同時作用于6個子layer,所以請留意self.animateCube.layer.sublayerTransform = transform中使用的是sublayerTransform而非transform
    self.containerView.layer.sublayerTransform = perspective;
  • 將6個View存儲到faces數組

1) face 1:正面---沿著Z軸的正方向平移100個單元

CATransform3D transform = CATransform3DMakeTranslation(0, 0, 100);
    [self addFace:0 withTransform:transform];

2) face 2:右邊的面 --- 沿著X軸的正方向平移100個單元 然后沿著Y軸逆時針旋轉90度

transform = CATransform3DMakeTranslation(100, 0, 0);
    transform = CATransform3DRotate(transform, M_PI_2, 0, 1, 0);
    [self addFace:1 withTransform:transform];

3) face 3:底面 --- 沿著Y軸的負方向平移100個單元 然后沿著X軸逆時針旋轉90度

transform = CATransform3DMakeTranslation(0, -100, 0);
    transform = CATransform3DRotate(transform, M_PI_2, 1, 0, 0);
    [self addFace:2 withTransform:transform];

4) face 4:頂面 --- 沿著Y軸的正方向平移100個單元 然后沿著X軸順時針旋轉90度

transform = CATransform3DMakeTranslation(0, 100, 0);
    transform = CATransform3DRotate(transform, -M_PI_2, 1, 0, 0);
    [self addFace:3 withTransform:transform];

5) face 5:左邊的面 --- 沿著X軸的負數方向平移100個單元 然后沿著Y軸順時針旋轉90度

transform = CATransform3DMakeTranslation(-100, 0, 0);
    transform = CATransform3DRotate(transform, -M_PI_2, 0, 1, 0);
    [self addFace:4 withTransform:transform];

6) face 6:背面 --- 沿著Z軸的負數方向平移100個單元 然后沿著Y軸順時針旋轉180度

transform = CATransform3DMakeTranslation(0, 0, -100);
    transform = CATransform3DRotate(transform, M_PI, 0, 1, 0);
    [self addFace:5 withTransform:transform];
  • -addFace:withTransform:函數
//獲取face視圖并將其添加到容器中
UIView *face = self.faces[index];
[self.containerView addSubview:face];

//將face視圖放在容器的中心
CGSize containerSize = self.containerView.bounds.size;
face.center = CGPointMake(containerSize.width / 2.0, containerSize.height / 2.0);

//添加transform
face.layer.transform = transform;
  • 添加定時器和回調函數
  1. 初始化定時器,并設置定時回調
self.angle = 0;
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)];
[self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
  1. 回調處理
//計算旋轉度數
self.angle = (self.angle + 5) % 360;

//將度數轉化為弧度
float deg = self.angle * (M_PI / 180);

// 初始化一個單元矩陣
CATransform3D temp = CATransform3DIdentity;

//將單元矩陣旋轉
temp = CATransform3DRotate(temp, deg, 0.3, 1, 0.7);

//旋轉容器的子layer
self.containerView.layer.sublayerTransform = temp;

CoreAnimation實現旋轉的立方體完整代碼參考:github

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,882評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,208評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 175,746評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,666評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,477評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,960評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,047評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,200評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,726評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,617評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,807評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,327評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,049評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,425評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,674評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,432評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,769評論 2 372