0

I have written a program to display an image using texture. I have added a button that I want to use to go to the next image. But I don't know which function I should call to go to next image. Can anyone help me please to know which function I should call in button(b) clicklistener?

MainActivity.java:

public class MainActivity extends Activity {
    Context context ;
    Square square = new Square();
    public Button b;
    /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE); 
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

        final GLSurfaceView view = new GLSurfaceView(this);
        final OpenGLRenderer openGLRenderer = new OpenGLRenderer(this);
        view.setRenderer(openGLRenderer);
        setContentView(view);
        context = this;
        b = new Button(this);
        b.setText("Next Image");
        b.setOnClickListener(new OnClickListener() {    
            @Override
            public void onClick(View arg0) {
            // TODO Auto-generated method stub          
            }
        });


         this.addContentView(b, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        }
  }

OpenGlRenderee:

public class OpenGLRenderer implements Renderer {
private Square      square;     // the square
private Context     context;

/** Constructor to set the handed over context */
public OpenGLRenderer(Context context) {
    this.context = context;

    this.square = new Square();
}


public void onSurfaceCreated(GL10 gl, EGLConfig config) {

square.loadGLTexture(gl, this.context);

gl.glEnable(GL10.GL_TEXTURE_2D);            //Enable Texture Mapping ( NEW )
gl.glShadeModel(GL10.GL_SMOOTH);            //Enable Smooth Shading
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.5f);    //Black Background
gl.glClearDepthf(1.0f);                     //Depth Buffer Setup
gl.glEnable(GL10.GL_DEPTH_TEST);            //Enables Depth Testing
gl.glDepthFunc(GL10.GL_LEQUAL);             //The Type Of Depth Testing To Do

//Really Nice Perspective Calculations
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
}


public void onDrawFrame(GL10 gl) {
    // Clears the screen and depth buffer.
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    // Replace the current matrix with the identity matrix
    gl.glLoadIdentity();
    // Translates 4 units into the screen.
    gl.glTranslatef(0, 0, -4); 
    // Draw our square.
    square.draw(gl); 
}

public void onSurfaceChanged(GL10 gl, int width, int height) {
    // Sets the current view port to the new size.
    gl.glViewport(0, 0, width, height);
    // Select the projection matrix
    gl.glMatrixMode(GL10.GL_PROJECTION);
    // Reset the projection matrix
    gl.glLoadIdentity();
    final float aspectRatio = width > height ?
            (float) width / (float) height :
            (float) height / (float) width;
            if (width > height) {
            // Landscape
                gl.glOrthof( -aspectRatio, aspectRatio, -1f, 1f, 0f, 0f);
                //gl.glOrthof(0f,  -aspectRatio,0,  aspectRatio, -1f, 1f);
            } else {
            // Portrait or square
            //gl.glOrthof( 0f,  -aspectRatio,0,  aspectRatio, -1f, 1f);
                gl.glOrthof( -1f, 1f, -aspectRatio, aspectRatio, 0f, 0f);
            }
    //gl.glOrthof(0f, (float) width / (float) height, 0f, (float) height / (float) width, -1f, 1f);
    // Calculate the aspect ratio of the window
    GLU.gluPerspective(gl, 45.0f, (float) width / (float) height, 0.1f,
            100.0f);
    // Select the modelview matrix
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    // Reset the modelview matrix
    gl.glLoadIdentity();
    }
 }

Square.java:

public class Square {

public static int numberOfImage = 0;

// Our vertices.
private float RectangleVertices[] = {
         // 0f,  0f,   // 0, Top Left
         // 0f, 14f,  // 1, Bottom Left
         //  9f, 14f, // 2, Bottom Right
         //  9f,  0f,  // 3, Top Right
        -0.5f, 0.5f,0.0f, // 0, Top Left
        -0.5f, -0.5f,0.0f, //1, Button Left
        0.5f, -0.5f,0.0f,//2,Button Right
        0.5f, 0.5f, 0.0f//3, Top Right

     };

int[] arr = {
        R.drawable.a,
        R.drawable.b,
        R.drawable.c,
        R.drawable.d,
        R.drawable.e,
        R.drawable.f,
        R.drawable.g,
        R.drawable.h,
        R.drawable.i,
        R.drawable.j,
        R.drawable.k,
        R.drawable.l,

};

float[] colors = {
1.0f, 1.0f, 1.0f, 1.0f,

0.7f, 0.7f, 0.7f, 1.0f,

1.0f, 1.0f, 1.0f, 1.0f,

0.7f, 0.7f, 0.7f, 1.0f,


};

private float LineVertices[] = {
        -0.5f, 0f,0.0f,
        0.5f, 0f,0.0f,
        0.0f,-0.25f,1.0f,
        0.0f,0.25f,1.0f,
};

// The order we like to connect them.
private short[] RectangleIndices = { 0, 1,2,0,2,3 };
private short[] LineIndices = {0,1};

// Our vertex buffer.
private FloatBuffer vertexBuffer;

// Our index buffer.
private ShortBuffer indexBuffer;


// Our vertex buffer.
private FloatBuffer vertexBuffer2;

// Our index buffer.
private ShortBuffer indexBuffer2;

FloatBuffer colorBuffer;// = makeFloatBuffer(colors);

//***************************************

//private FloatBuffer vertexBuffer; // buffer holding the vertices

private float vertices[] = {
        -1.0f, -1.0f,  0.0f,        // V1 - bottom left
        -1.0f,  1.0f,  0.0f,        // V2 - top left
         1.0f, -1.0f,  0.0f,        // V3 - bottom right
         1.0f,  1.0f,  0.0f         // V4 - top right
};
private FloatBuffer textureBuffer;  // buffer holding the texture coordinates
private float texture[] = {         
        // Mapping coordinates for the vertices
        0.0f, 1.0f,     // top left     (V2)
        0.0f, 0.0f,     // bottom left  (V1)
        1.0f, 1.0f,     // top right    (V4)
        1.0f, 0.0f      // bottom right (V3)
};


//***************************************
public Square() {
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(vertices.length * 4); 
byteBuffer.order(ByteOrder.nativeOrder());
vertexBuffer = byteBuffer.asFloatBuffer();
vertexBuffer.put(vertices);
vertexBuffer.position(0);

byteBuffer = ByteBuffer.allocateDirect(texture.length * 4);
byteBuffer.order(ByteOrder.nativeOrder());
textureBuffer = byteBuffer.asFloatBuffer();
textureBuffer.put(texture);
textureBuffer.position(0);
}

public void draw(GL10 gl) {
    // bind the previously generated texture
    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

    // Point to our buffers
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

    // Set the face rotation
    gl.glFrontFace(GL10.GL_CW);

    // Point to our vertex buffer
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
    gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);

    // Draw the vertices as triangle strip
    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, vertices.length / 3);

    //Disable the client state before leaving
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}




///*****************************************

/** The texture pointer */
private int[] textures = new int[1];

public void loadGLTexture(GL10 gl, Context context) {
    // 

    //loading texture
    // pull in the resource
    Bitmap bitmap = null;
    Resources resources = context.getResources();

    Drawable image = resources.getDrawable( arr[numberOfImage]);
    float density = resources.getDisplayMetrics().density;

    int originalWidth = (int)(image.getIntrinsicWidth() / density);
    int originalHeight = (int)(image.getIntrinsicHeight() / density);


    bitmap = decodeSampledBitmapFromResource(context.getResources(),
            arr[numberOfImage],originalWidth, originalHeight );

    // generate one texture pointer
    gl.glGenTextures(1, textures, 0);
    // ...and bind it to our array
    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

    // create nearest filtered texture
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

    // Use Android GLUtils to specify a two-dimensional texture image from our bitmap 
    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

    // Clean up
    bitmap.recycle();

    if(numberOfImage == arr.length - 1)
        numberOfImage = 0;
    else
        numberOfImage ++;

}


 public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,int reqWidth, int reqHeight) {

     final BitmapFactory.Options options = new BitmapFactory.Options();
     options.inJustDecodeBounds = true;
     BitmapFactory.decodeResource(res, resId, options);

     options.inSampleSize = calculateInSampleSize(options, reqWidth,
             reqHeight);

     // Decode bitmap with inSampleSize set
     options.inJustDecodeBounds = false;
     Bitmap bmp = BitmapFactory.decodeResource(res, resId, options);
     return BitmapFactory.decodeResource(res, resId, options);

 }

  public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {

        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
             }
         }
         return inSampleSize;

  }
}
genpfault
  • 51,148
  • 11
  • 85
  • 139
  • Not really sure what you are trying to accomplish. Are you talking about an view pager example? – portfoliobuilder Mar 20 '15 at 16:34
  • @portfoliobuilder I mean I want to change the image which is diplaying. –  Mar 20 '15 at 16:37
  • @portfoliobuilder there are some images in R.Drawable. I want to switch between them with this button –  Mar 20 '15 at 16:38
  • You can either set the imageView to another image or if you want a swiping feel, implement a view pager. To set image, retrieve your drawable with Drawable mDrawable = getResources().getDrawable(R.drawable.imageView); and then reference your ImageView and use setImageDrawable(mDrawable) – portfoliobuilder Mar 20 '15 at 16:38
  • @portfoliobuilder can you please give me a link to see what the view pager is? And don't you have any idea doing this with these methods? –  Mar 20 '15 at 16:40
  • Sure, I will write an example for you – portfoliobuilder Mar 20 '15 at 16:41

1 Answers1

-1

To change an image to a different drawable, you only have to set your imageView to that new image

ImageView iv=(ImageView) findViewById(R.id.iv);
Drawable mDrawable = getResources().getDrawable(R.drawable.iv);
iv.setImageDrawable(mDrawable);

You mentioned a "slider", to me that sounds like you may be interested in a ViewPager. You can create a view pager adapter, and use that to load up your images and the user can swipe the images left to right, or you can have the images change by button press if you like.

public class ViewPagerAdapter extends PagerAdapter {

private Context mContext;
private int[] mArr;
private Button btnRight; // move to next
private Button btnLeft; // move to prev

/**
* @param int[] array of your drawables
*/ 
public ViewPagerAdapter(Context context, int[] arr) 
   this.mContext = context;
   this.mArr = arr;
}

@Override
public int getCount() {
   return mArr.length();
}

@Override 
public boolean isViewFromObject(View view, Object object) {
   return view = ((LinearLayout) object); // whatever your main view is ll or rl
}

@Override 
public Object instantiateItem(final ViewGroup container, final int position) {
   LayoutInflater inflater = (LayoutInflater) mContext.
      getSystemService(Context.LAYOUT_INFLATER_SERVICE);

   // to setup buttons to change position of pager
   btnLeft = (Button) itemView.findViewById(R.id.btn_left);
   btnLeft.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
         // setup your logic for swiping changing views
         // for example
         // ref: http://stackoverflow.com/questions/21368693/how-to-do-circular-scrolling-on-viewpager/24244144#24244144    
         int meta = ((ViewPager) container.getCurrentItem() - 1;
         if (meta == 0) {
              ((ViewPager) container).setCurrentItem(mArr.length - 1, false);
         } else {
              ((ViewPager) container).setCurrentitem(meta);
         }
      } 
   });

   btnRight = (Button) itemView.findViewById(R.id.btn_right);
   btnRight.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
         // setup your logic for swiping changing views
         // for example

         int meta = ((ViewPager) container.getCurrentItem() - 1;
         if (meta == mArr.length - 1) {
              ((ViewPager) container).setCurrentItem(1, false);
         } else {
              ((ViewPager) container).setCurrentitem(meta);
         }
      } 
   });

   // to listen for swiping of pager
   ((ViewPager) container).setOnPageChangeListener(new OnPageChangeListener() {
      @Override
      public void onPageSelected(int pos) {
         // add whatever logic you need
         // for example

         if (pos == 0) {
            ((ViewPager) container).setCurrentItem(mArr.length - 1, true);
         } else if (pos == mArr.length - 1) {
            ((ViewPager) container).setcurrentItem(1, true);
         }

         // can add other useful override
         @Override
         public void onPagescrollStateChanged(int state) {}

         @Override
         public void onPageScrolled(int pos, float posOffset, int posOffsetPixeles) {}

      });

      }

   }
}

In your main activity call and set your adapter. For example

ViewPager viewPager = (ViewPager) findviewById(R.id.pager);
PagerAdapter adapter = new ViewPagerAdapter(context, mArr);
viewPager.setAdapter(adapter);

Hopefully this is what you were asking for. Let me know if there are any questions.

portfoliobuilder
  • 7,556
  • 14
  • 76
  • 136