andbook!.pdf - Learning Android Get an anddev.org - Android-Shirt Back to index
anddev.org Header Logo
FAQ Search Top rated articles Browse Feeds anddev.org - Authors Contact Details Register Log in

Scrolling a Picture (horizontally and vertically)


 
       anddev.org - Android Development Community | Android Tutorials | Index -> Advanced Tutorials
Author Message
Danuubz
Experienced Developer
Experienced Developer


Joined: 19 Dec 2007
Posts: 75
Location: Germany

PostPosted: Thu Oct 23, 2008 12:33 pm    Post subject: Scrolling a Picture (horizontally and vertically) Reply with quote

I've written a small code example which shows how to make a picture scrollable by hand. You can scroll it by dragging it with the mouse (or finger).

In this case, the picture has to be sized exactly [800x600], named like 'pic.jpg' or 'pic.png' and it should be placed in the folder 'res>drawable>' of your project.

Actually, making more complex views scrollable by hand should work the same way. However the coordinates of each component and its behavior have to be adapted after every single scroll movement. So if there's a way making it out of the box, that would be the preferable choice of course Very Happy


Java:
package de.horizontalscroll;

import de.horizontalscroll.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.view.GestureDetector.OnGestureListener;
import android.content.*;
import android.graphics.*;
import android.content.res.*;

public class HorizontalScroll extends Activity implements OnGestureListener
{
     private static final int X_MAX = 800;
     private static final int Y_MAX = 600;
     private int scrollX = 0;
    private int scrollY = 0;
     
    MyView main;  
    Bitmap bmp;
    Bitmap adapt;
    Resources res;
    Paint paint;
    GestureDetector gestureScanner;
     
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
       
        gestureScanner = new GestureDetector(this);
        paint = new Paint();
       
        res = getResources();
        bmp = BitmapFactory.decodeResource(res, R.drawable.pic);
        adapt = Bitmap.createBitmap(bmp);
             
        main = new MyView(this);        
        setContentView(main,new ViewGroup.LayoutParams(800,600));
    }
   
    @Override
    public boolean onTouchEvent(MotionEvent me)
    {
     return gestureScanner.onTouchEvent(me);
    }
   
    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
    {
     main.handleScroll(distanceX,distanceY);
     return true;
    }
   
    ////////////////////
    ///////////////////
    //////////////////
    @Override
    public boolean onDown(MotionEvent e)
    {
     return true;
    }
   
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
    {
     return true;
    }
   
    @Override
    public void onLongPress(MotionEvent e){    }
   
    @Override
    public void onShowPress(MotionEvent e) {   }    
   
    @Override
    public boolean onSingleTapUp(MotionEvent e)    
    {
     return true;
    }
    ////////////////////
    ///////////////////
    //////////////////
   
    class MyView extends View
    {
     public MyView(Context context)
     {
          super(context);
     }
     
     @Override
     protected void onDraw(Canvas canvas)
     {
          canvas.drawBitmap(adapt, 0, 0, paint);
     }
     
     public void handleScroll(float distX, float distY)
     {
          // X-Axis ////////////////////////////////
          
          if(distX > 6.0)
          {
               if(scrollX < 460)
               {
                    scrollX += 15;
               }
          }
          else if(distX < -6.0)
          {
               if(scrollX >= 15)
               {
                    scrollX -= 15;
               }
          }
          ////////////////////////////////////////////
               
          // Y-AXIS //////////////////////////////////
          if(distY > 6.0)
          {
               if(scrollY < 100)
               {
                    scrollY += 15;
               }
          }
          else if(distY < -6.0)
          {
               if(scrollY >= 15)
               {
                    scrollY -= 15;
               }
          }              
          ////////////////////////////////////////////
          
          if((scrollX <= 480) && (scrollY <= 120))
          {
               adapt = Bitmap.createBitmap(bmp, scrollX, scrollY, 320, 480);              
               invalidate();
          }
     }
    }
}
Back to top
View user's profile Send private message
ravi
Freshman
Freshman


Joined: 04 Nov 2008
Posts: 8

PostPosted: Thu Nov 13, 2008 12:16 am    Post subject: Reply with quote

Thanks for the tutorial, it was helpful to me!
Back to top
View user's profile Send private message
weldrian
Junior Developer
Junior Developer


Joined: 09 Dec 2008
Posts: 23

PostPosted: Tue Dec 09, 2008 9:12 am    Post subject: Help Reply with quote

Can you please help me solve the problem ?
Please.please refer the pic below!



1.png
 Description:
 Filesize:  104.12 KB
 Viewed:  16341 Time(s)

1.png


Back to top
View user's profile Send private message
jinez
Once Poster
Once Poster


Joined: 09 Dec 2008
Posts: 1

PostPosted: Tue Dec 09, 2008 8:25 pm    Post subject: Re: Help Reply with quote

hello weldrian!

I think ur package name in code is not match with ur package name.

Ur package name is "com.a.a", but "de.horazontalscroll" is package name in ur code.

try to fix "de.horazontalscroll" to "com.a.a"
Back to top
View user's profile Send private message
Danuubz
Experienced Developer
Experienced Developer


Joined: 19 Dec 2007
Posts: 75
Location: Germany

PostPosted: Fri Dec 12, 2008 4:52 pm    Post subject: Reply with quote

Additonally you have to delete 'import de.horizontalscroll.R'.
_________________
Check my app on Youtube: http://www.youtube.com/watch?v=j8ZHq8ZOvtM
Back to top
View user's profile Send private message
weldrian
Junior Developer
Junior Developer


Joined: 09 Dec 2008
Posts: 23

PostPosted: Fri Dec 12, 2008 4:55 pm    Post subject: another problem Reply with quote

hi man,

i hav solve the package problem, but i cant see anything on my picture folder.
i think you have to teach me how to upload or put pic on the emulator.

what i mean is, when i compile to the emulator, there have no pic showing on the picture folder,
actually what i m trying to do is..

1: put pic on the folder
2: zoom in, zoom out
3: slider for next pic
4: rotating.

do you think possible? can you do it? can you teach me?
Back to top
View user's profile Send private message
Danuubz
Experienced Developer
Experienced Developer


Joined: 19 Dec 2007
Posts: 75
Location: Germany

PostPosted: Fri Dec 12, 2008 7:29 pm    Post subject: Reply with quote

Hello,

Generally it is possible. To implement step 2-4 may need some time. I'm rather busy with other projects, so currently I cannot make these steps for you.

Loading a picture into the app should be no problem:
1.) Put the image into ProjectFolder/res/drawable/
2.) Now you load it with bmp = BitmapFactory.decodeResource(res, R.drawable.pic);

if the picture has the name other.jpg then you load it with
bmp = BitmapFactory.decodeResource(res, R.drawable.other);

3.) my example is made for a picture sized 800x600. If you would like to take one with other size, you need to adapt the code on several places.

_________________
Check my app on Youtube: http://www.youtube.com/watch?v=j8ZHq8ZOvtM
Back to top
View user's profile Send private message
cdspace
Once Poster
Once Poster


Joined: 18 Dec 2008
Posts: 1

PostPosted: Thu Dec 18, 2008 1:26 am    Post subject: Thank you Reply with quote

Thank you so much for this. I've been trying to figure this out for a week. This is exactly what I've been trying to do.
_________________
The Code Demon Rises
Back to top
View user's profile Send private message
MrSnowflake
Moderator
Moderator


Joined: 16 Feb 2008
Posts: 1437
Location: Flanders, Belgium

PostPosted: Thu Dec 18, 2008 1:52 am    Post subject: Reply with quote

You should have come here earlier Smile.
Back to top
View user's profile Send private message
weldrian
Junior Developer
Junior Developer


Joined: 09 Dec 2008
Posts: 23

PostPosted: Fri Dec 19, 2008 8:02 am    Post subject: thx Reply with quote

hey all,

when i compile to the emulator, the system show," the app close unexpectedly,"
but is ok, i will try to fingure out what is the problem. Thx for your soure.

now i m learning zoom in and zoom out!
Back to top
View user's profile Send private message
pjv
Developer
Developer


Joined: 19 Aug 2008
Posts: 37

PostPosted: Sat Jan 24, 2009 12:58 pm    Post subject: Reply with quote

I've concocted a version of ScrollView that also does horizontal scrolling. It works quite well when containing only one TextView but was NOT tested apart from that. Probably still has many bugs, but at least it's a starting point to improve on for anyone facing the same problem of the only-vertically scrolling ScrollView. Code is here: http://bazaar.launchpad.net/~pjv/androidsfortune/trunk/annotate/head%3A/src/net/lp/androidsfortune/utils/FullScrollView.java.
Back to top
View user's profile Send private message
wormhole009
Once Poster
Once Poster


Joined: 19 Dec 2009
Posts: 1

PostPosted: Sat Dec 19, 2009 11:53 pm    Post subject: Cleaned up version Reply with quote

Here's a little more cleaned up version (and works for the Droid), but still needs work. The package visibility and lack of getter/setter is because of Android's crappy compiler (see their "Performance" dev page).

Java:


import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.GestureDetector.OnGestureListener;
import android.view.ViewGroup.LayoutParams;

public class Timeline extends Activity {
   
   ScrollableImageView scrollImageView;
   
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
     
      WindowManager w = getWindowManager();
      Display d = w.getDefaultDisplay();
     
      scrollImageView = new ScrollableImageView(this,
            BitmapFactory.decodeResource(getResources(), R.drawable.rocks),
            d.getWidth(), d.getHeight(),
            null);
      setContentView(scrollImageView);
   }
   
   public boolean onTouchEvent(MotionEvent event) {
      return scrollImageView.getGestureScanner().onTouchEvent(event);
   }
   
   ////
   ////

   class ScrollableImageView extends View {
     
      int scrollRate = 40;
     
      int scrollX = 0;
     
      int scrollY = 0;
     
      boolean scrollHorizontalEnabled = true;
     
      boolean scrollVerticalEnabled = true;
     
      ////
     
      Bitmap image;
     
      Bitmap bufferImage;
     
      int maxWidth;
     
      int maxHeight;
     
      int pictureWidth;
     
      int pictureHeight;
     
      ////
     
      Paint paint;
     
      GestureDetector gestureScanner;
     
      ////
      ////

      public ScrollableImageView(Context context, Bitmap image, int width,
            int height, Paint paint) {
         super(context);
         this.image = image;
         this.paint = paint;
         
         bufferImage = Bitmap.createBitmap(image);
         
         calculateSize(width, height);
         createGestureListener();
      }
     
      public ScrollableImageView(Context context, Bitmap image,
            int width, int height, Paint paint,
            boolean scrollHorizontal, boolean scrollVertical) {
         super(context);
         this.image = image;
         this.paint = paint;
         this.scrollHorizontalEnabled = scrollHorizontal;
         this.scrollVerticalEnabled = scrollVertical;
         
         bufferImage = Bitmap.createBitmap(image);
         
         calculateSize(width, height);
         createGestureListener();
      }
     
      protected void calculateSize(int width, int height) {
         
         //picture size
         pictureWidth = image.getWidth();
         pictureHeight = image.getHeight();
         
         //window size
         maxWidth = Math.min(pictureWidth, width);
         maxHeight = Math.min(pictureHeight, height);
         
         //layout size
         setLayoutParams(new LayoutParams(pictureWidth, pictureHeight));
      }
     
      protected void createGestureListener(){
         setGestureScanner(new GestureDetector(new OnGestureListener() {
           
            public boolean onScroll(MotionEvent event1, MotionEvent event2,
                  float distanceX, float distanceY) {
               handleScroll(distanceX, distanceY);
               return true;
            }

            public boolean onDown(MotionEvent event) {
               return true;
            }
           
            public boolean onFling(MotionEvent event1, MotionEvent event2,
                  float velocityX, float velocityY) {
               return true;
            }

            public void onLongPress(MotionEvent event) {
               //do nothing
            }

            public void onShowPress(MotionEvent event) {
               //do nothing
            }

            public boolean onSingleTapUp(MotionEvent event) {
               return true;
            }
         }));
      }

      @Override
      protected void onDraw(Canvas canvas) {
         canvas.drawBitmap(bufferImage, 0, 0, paint);
      }

      protected void handleScroll(float distX, float distY) {
         
         int maxScrollX = Math.max(pictureWidth - maxWidth, 0);
         int maxScrollY = Math.max(pictureHeight - maxHeight, 0);
         
         //X-Axis
         if(scrollHorizontalEnabled){
            if (distX > 6.0) {
               if (scrollX < maxScrollX - scrollRate) {
                  scrollX += scrollRate;
               }
               else {
                  scrollX = maxScrollX;
               }
            } else if (distX < -6.0) {
               if (scrollX >= scrollRate) {
                  scrollX -= scrollRate;
               }
               else {
                  scrollX = 0;
               }
            }
         }

         //Y-AXIS
         if(scrollVerticalEnabled){
            if (distY > 6.0) {
               if (scrollY < maxScrollY - scrollRate) {
                  scrollY += scrollRate;
               }
               else {
                 
               }
            } else if (distY < -6.0) {
               if (scrollY >= scrollRate) {
                  scrollY -= scrollRate;
               }
               else {
                  scrollY = 0;
               }
            }
         }
         
         //Swap image
         if ((scrollX <= maxWidth) && (scrollY <= maxHeight)) {
            swapImage();
            invalidate();
         }
      }
     
      protected void swapImage() {
         bufferImage = Bitmap.createBitmap(image, scrollX, scrollY,
               maxWidth, maxHeight);
      }

      /**
       * @return the gestureScanner
       */

      public GestureDetector getGestureScanner() {
         return gestureScanner;
      }

      /**
       * @param gestureScanner the gestureScanner to set
       */

      public void setGestureScanner(GestureDetector gestureScanner) {
         this.gestureScanner = gestureScanner;
      }
   }
}
Back to top
View user's profile Send private message
Display posts from previous:   
       anddev.org - Android Development Community | Android Tutorials | Index -> Advanced Tutorials All times are GMT + 1 Hour
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


© 2007, Android Development Community
All rights reserved.
Powered by phpBB.