6

I'm creating a live wallpaper with parallax scrolling. I've read the article: Parallax effect scrolling of live wallpaper background. But when I change desktops the background moves wrong way (If I change desktop from left to right, picture moves from right to left). How to change direction? Code snippet:

public void Init(Bitmap bitmap){
  bg = new BitmapFactory().decodeResource(context.getResources(), R.drawable.thunder);
  bg = Bitmap.createScaledBitmap(bg, (int)(width*1.4), height, true);
}

float dx = 0.0f; 
@Override
    public void onOffsetsChanged(float xOffset, float yOffset,
            float xStep, float yStep, int xPixels, int yPixels) {
        dx = (width - bg.getWidth()) * (1 - xOffset);
    } 

private void doDraw(Canvas canvas) {
    canvas.save();
    canvas.translate(dx, 0);
    canvas.drawBitmap(bg, 0, 0, null);

    canvas.restore();
}   
Community
  • 1
  • 1
Nolesh
  • 6,848
  • 12
  • 75
  • 112

3 Answers3

4

I know this is an old issue, but since this is a high result on Google, all you need to do to is flip the sign on your translate.

canvas.translate(-dx, 0);

This will effectively reverse the direction the background scrolls when the user swipes. Hope this helps others.

Jawnnypoo
  • 993
  • 12
  • 18
1

The algorithm here needs to be changed:

dx = (width - bg.getWidth()) * (1 - xOffset);

Should be changed to something similar to:

dx = (width) * (xOffset);

An alternative would be to access the canvas.drawBitmap() method directly through something like this:

canvas.drawBitmap(bg, xPixels, 0, null);
Music Monkey
  • 340
  • 4
  • 15
0

dx = (width - bg.getWidth()) * xOffset;

where:

width - canvas width;
bg - bitmap

  • This works, but how do I cause the scrolling to cause the canvas reach the edges of the background, only on the first and last home pages? – android developer Nov 05 '17 at 23:32