1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.example.android.opengl;
17 
18 import android.content.Context;
19 import android.opengl.GLSurfaceView;
20 import android.view.MotionEvent;
21 
22 /**
23  * A view container where OpenGL ES graphics can be drawn on screen.
24  * This view can also be used to capture touch events, such as a user
25  * interacting with drawn objects.
26  */
27 public class MyGLSurfaceView extends GLSurfaceView {
28 
29     private final MyGLRenderer mRenderer;
30 
MyGLSurfaceView(Context context)31     public MyGLSurfaceView(Context context) {
32         super(context);
33 
34         // Set the Renderer for drawing on the GLSurfaceView
35         mRenderer = new MyGLRenderer();
36         setRenderer(mRenderer);
37 
38         // Render the view only when there is a change in the drawing data
39         setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
40     }
41 
42     private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
43     private float mPreviousX;
44     private float mPreviousY;
45 
46     @Override
onTouchEvent(MotionEvent e)47     public boolean onTouchEvent(MotionEvent e) {
48         // MotionEvent reports input details from the touch screen
49         // and other input controls. In this case, we are only
50         // interested in events where the touch position changed.
51 
52         float x = e.getX();
53         float y = e.getY();
54 
55         switch (e.getAction()) {
56             case MotionEvent.ACTION_MOVE:
57 
58                 float dx = x - mPreviousX;
59                 float dy = y - mPreviousY;
60 
61                 // reverse direction of rotation above the mid-line
62                 if (y > getHeight() / 2) {
63                     dx = dx * -1 ;
64                 }
65 
66                 // reverse direction of rotation to left of the mid-line
67                 if (x < getWidth() / 2) {
68                     dy = dy * -1 ;
69                 }
70 
71                 mRenderer.setAngle(
72                         mRenderer.getAngle() +
73                         ((dx + dy) * TOUCH_SCALE_FACTOR));  // = 180.0f / 320
74                 requestRender();
75         }
76 
77         mPreviousX = x;
78         mPreviousY = y;
79         return true;
80     }
81 
82 }
83